码迷,mamicode.com
首页 > 编程语言 > 详细

go语言---reflect

时间:2018-07-08 22:11:03      阅读:179      评论:0      收藏:0      [点我收藏+]

标签:结构体   etc   根据   tail   port   对象   类型   art   type   

go语言---reflect

https://blog.csdn.net/cyk2396/article/details/78902953

一.reflect的使用:

import (
    "fmt"
    "reflect"
)
 
type Student struct {
    Name string
    Age  int
}
 
func main() {
    var x int = 1
    student := Student{Name: "zs", Age: 26}
 
    //1.reflect.TypeOf() 返回值Type类型
    fmt.Println("x type: ", reflect.TypeOf(x))
    fmt.Println("student type: ", reflect.TypeOf(student))
 
    //2.reflect.ValueOf() 返回值Value类型
    fmt.Println("x value: ", reflect.ValueOf(x))
    fmt.Println("student value: ", reflect.ValueOf(student))
 
    //3.value.Kind() 返回值Kind类型 注意与Type的不同
    fmt.Println("x kind: ", reflect.ValueOf(x).Kind())
    fmt.Println("student kind: ", reflect.ValueOf(student).Kind())
 
    //4.修改反射对象,修改反射对象的前提条件是其值是可设置的
    var a int = 10
    v := reflect.ValueOf(&a)
    e := v.Elem()
    e.SetInt(15)
    fmt.Println(e.CanSet()) //根据CanSet()返回值可确定是否可以设置
    fmt.Println(a)          // 根据结果我们可知 a=15
 
    //5.遍历结构体字段内容
    s := reflect.ValueOf(&student).Elem()
    studentType := s.Type()
    for i := 0; i < s.NumField(); i++ {
        f := s.Field(i)
        fmt.Printf("%d %s %s = %v\n", i, studentType.Field(i).Name, f.Type(), f.Interface())
    }
}

输出结果:

x type: int
student type: main.Student
x value: 1
student value: {zs 26}
x kind: int
student kind: struct
true
15
0 Name string = zs
1 Age int = 26

go语言---reflect

标签:结构体   etc   根据   tail   port   对象   类型   art   type   

原文地址:https://www.cnblogs.com/Leo_wl/p/9281298.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!