go语言---reflect

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
", 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

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