反射
反射的基本函数
package main
import (
"fmt"
"reflect"
)
func main() {
var n int64 = 10
// 获取变量类型信息 reflect.Type
rTyp := reflect.TypeOf(n)
fmt.Printf("rType: type=%T, toString=%s\n", rTyp, rTyp.String())
// 获取变量值信息 reflect.Value
rVal := reflect.ValueOf(n)
fmt.Printf("rVal: type=%T, toString=%s, originValue=%d\n", rVal, rVal.String(), rVal.Int()) // 转换为原始类型,如果调用的方法与实际类型不匹配,会发生panic异常
// 获取变量对应的kind,type代表变量的具体类型,而kind代表变量的分类类型
// 如果是基本类型,kind==type,比如 kind=int64 type=int64
// 如果不是基本类型,比如struct,type与kind一般不同,比如 kind=struct type=main.Student
kind1 := rTyp.Kind()
kind2 := rVal.Kind()
fmt.Printf("kind=%s, %s", kind1, kind2)
// 根据 rVal 获取变量值,因为不知道是什么类型,所以以interface的方式返回
iV := rVal.Interface()
fmt.Printf("iV: type=%T, originValue=%v\n ", iV, iV)
// 将interface{} 通过断言转换成需要的类型
n2 := iV.(int64)
fmt.Println(n2)
}通过反射修改值
反射操作方法与函数
最后更新于