go 学习之反射

TypeOf() 函数用来提取一个接口中值的类型信息。由于它的输入参数是一个空的 interface{},调用此函数时,实参会先被转化为 interface{}类型。这样,实参的类型信息、方法集、值信息都存储到 interface{} 变量里了
ValueOf() 返回值 reflect.Value 表示 interface{} 里存储的实际变量,它能提供实际变量的各种信息。相关的方法常常是需要结合类型信息和值信息。
注意事项:
reflect.Vlaue.Kind,reflect.Type.Kind,获取变量的类别,返回的是一个常量
Type 是类型,Kind是类别,Type和Kind可能相同,也可能不同
如: var num int = 10 num的Type是int,Kind也是int
var stu Student stu的Type是pkg1.Student,Kind是struct
通过反射可以让变量在interface{}和Reflect.Value之间相互转换
使用反射的方式来获取变量的值,要求数据类型匹配,比如x是int,那么就应该使用reflect.Value(x).Int()
package main

import (
        "reflect"
        "fmt"
)

type Student struct {
        name string
        age int
}

func reflectTest(b interface{}) {
        rType := reflect.TypeOf(b)
        rVal := reflect.ValueOf(b)
        iv := rVal.Interface()
        stu := iv.(Student)
        fmt.Printf("type: %T, vtype:%T, name: %v, age:%d
", rType, rVal, stu.name, stu.age)
}

func main() {
        stu := Student{"caoxt", 30}
        reflectTest(stu)
}

  




原文地址:https://www.cnblogs.com/Caoxt/p/14162867.html