reflect库不常用,所有每次用的时候都要翻看文档,为了方便自己,特定写个例子
package main
import (
"log"
"reflect"
)
type Info struct {
Id int
}
func Log(format string, args ...interface{}) {
log.Printf(format+"\n", args...)
}
func main() {
log.SetFlags(log.Ldate | log.Lshortfile) //
var i Info
t := reflect.TypeOf(i)
Log("name:%s", t.Name())
Log("string:%+v", t.String())
Log("kind:%+v", t.Kind())
Log("pkgPath:%+v", t.PkgPath())
v := reflect.ValueOf(i)
Log("value:%+v", v.FieldByName("Id").Int())
Log("value:%+v", v.FieldByName("Id").Interface())
Log("split%s", "====")
s := &i
t = reflect.TypeOf(s)
Log("kind of t:%+v", t.Kind())
switch t.Kind() {
case reflect.Ptr:
Log("pt:%+v", "")
case reflect.Struct:
Log("struct:%+v", "")
}
t = reflect.Indirect(reflect.ValueOf(s)).Type()
Log("name:%s", t.Name())
Log("string:%+v", t.String())
Log("kind:%+v", t.Kind())
Log("pkgPath:%+v", t.PkgPath())
}
上面的代码执行结果如下:
2019/06/08 main.go:13: name:Info
2019/06/08 main.go:13: string:main.Info
2019/06/08 main.go:13: kind:struct
2019/06/08 main.go:13: pkgPath:main
2019/06/08 main.go:13: value:0
2019/06/08 main.go:13: value:0
2019/06/08 main.go:13: split====
2019/06/08 main.go:13: kind of t:ptr
2019/06/08 main.go:13: pt:
2019/06/08 main.go:13: name:Info
2019/06/08 main.go:13: string:main.Info
2019/06/08 main.go:13: kind:struct
2019/06/08 main.go:13: pkgPath:main
有疑问加站长微信联系(非本文作者)