反射reflect
1、序列化的时候指定key的名字
2、
1、在运行时动态获取变量的各种信息,比如变量的类型(type)类别(kind) 2、如果是结构体变量,还可以获取到结构体本身的信息(字段、方法) 3、通过反射们可以修改变量的值,可以调用关联的方法 4、reflect
类型(Type)和种类(Kind)的区别。编程中,使用最多的是类型,但在反射中,当需要区分一个大品种的类型时,就会用到种类(Kind)。例如,需要统一判断类型中的指针时,使用种类(Kind)信息就较为方便
Go 程序中的类型(Type)指的是系统原生数据类型,如 int、string、bool、float32 等类型,以及使用 type 关键字定义的类型,这些类型的名称就是其类型本身的名称。例如使用 type A struct{} 定义结构体时,A 就是 struct{} 的类型。 种类(Kind)指的是对象归属的品种
type Kind uint const ( Invalid Kind = iota // 非法类型 Bool // 布尔型 Int // 有符号整型 Int8 // 有符号8位整型 Int16 // 有符号16位整型 Int32 // 有符号32位整型 Int64 // 有符号64位整型 Uint // 无符号整型 Uint8 // 无符号8位整型 Uint16 // 无符号16位整型 Uint32 // 无符号32位整型 Uint64 // 无符号64位整型 Uintptr // 指针 Float32 // 单精度浮点数 Float64 // 双精度浮点数 Complex64 // 64位复数类型 Complex128 // 128位复数类型 Array // 数组 Chan // 通道 Func // 函数 Interface // 接口 Map // 映射 Ptr // 指针 Slice // 切片 String // 字符串 Struct // 结构体 UnsafePointer // 底层指针 )
//变量、接口、refect.Value是可以相互转换的 var a int = 9 //interface ---> reflect.Value var b interface{} b = a rVal := reflect.ValueOf(b) // rVal是一个reflect.Value的类型 //reflect.Value ---> interface Val := rVal.Interface() //interface ---> int c := Val.(int) fmt.Println(c)
1