golang reflect
发布时间:2020-12-16 09:32:24 所属栏目:大数据 来源:网络整理
导读:在计算机中,反射表示程序能够检查自身结构的一种能力,尤其是类型。通过反射,可以获取对象类型的详细信息,并可动态操作对象。 实现 包手册地址:https://studygolang.com/static/pkgdoc/pkg/reflect.htm Import ("reflect") 常用的主要有?type value kind
在计算机中,反射表示程序能够检查自身结构的一种能力,尤其是类型。通过反射,可以获取对象类型的详细信息,并可动态操作对象。 实现 包手册地址:https://studygolang.com/static/pkgdoc/pkg/reflect.htm Import ("reflect") 常用的主要有?type value kind reflect.TypeOf?获取变量的类型,返回reflect.Type类型 reflect.Value.Kind,获取变量的类别,返回一个常量 package main import ( "fmt" "reflect" ) type user struct { name string id int age uint8 } func (u user) hello() { fmt.Println("hello world") } func info(o interface{}) { t := reflect.TypeOf(o) fmt.Println(t.Kind()) //kind返回类型的常量 fmt.Println(t) //TypeOf返回的是类型 package.type } func main() { var stu = user{ name: "zhangsan",id: 1,age: 22,} stu.hello() info(stu) info("string") } ? package main import ( "fmt" "reflect" ) type user struct { name string id int age uint8 } func (u user) hello() { fmt.Println("hello world") } func info(o interface{}) { v := reflect.ValueOf(o) iv := v.Interface() if typ,ok := iv.(user); ok == false { fmt.Printf("断言的type为%T,o的type为%Tn",typ,iv) } else { fmt.Println("断言成功") } } func main() { var stu = user{ name: "zhangsan",} info(15) info(stu) } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |