package main import ( "fmt" "reflect" ) func main() { x := "hello world" p := reflect.TypeOf(x) v := reflect.ValueOf(x) fmt.Println("typeof:", p, " valueof type:", v.Type(), " valueof kind:", v.Kind()) //pp := reflect.TypeOf(&x) vv := reflect.ValueOf(&x) fmt.Println("vv.Type=", vv.Type(), " vv.Kind=", vv.Kind()) }
TypeOf() 与 ValueOf 得到的值调用Type() 返回结果是一样的
但ValueOf得到的值调用Kind()可能一样,因为如果是第二种情况(指针情况), vv.Kind() 打印出来是ptr,而不是 *string
package main import ( "fmt" "reflect" ) func main() { x := "hello world" p := reflect.TypeOf(x) v := reflect.ValueOf(x) fmt.Println("typeof:", p, " valueof type:", v.Type(), " valueof kind:", v.Kind()) //pp := reflect.TypeOf(&x) vv := reflect.ValueOf(&x) fmt.Println("vv.Type=", vv.Type(), " vv.Kind=", vv.Kind(), " vv.Elem=", vv.Elem())// vv.Elem() 返回hello world elem := vv.Elem() fmt.Println("valueof.CanSet=", vv.CanSet(), " valueof.Elem.CanSet=", elem.CanSet())//第一个返回false,第二个返回true }
type T struct { A int B string } func main() { x := "hello world" p := reflect.TypeOf(x) v := reflect.ValueOf(x) fmt.Println("typeof:", p, " valueof type:", v.Type(), " valueof kind:", v.Kind()) //pp := reflect.TypeOf(&x) vv := reflect.ValueOf(&x) fmt.Println("vv.Type=", vv.Type(), " vv.Kind=", vv.Kind(), " vv.Elem=", vv.Elem()) elem := vv.Elem() fmt.Println("valueof.CanSet=", vv.CanSet(), " valueof.Elem.CanSet=", elem.CanSet()) fmt.Println("******************************") t := T {A:123, B:"hello world"} vf := reflect.ValueOf(&t) fmt.Println("typeof(t)=", reflect.TypeOf(t), " vf.Type=", vf.Type(), " vf.Kind=", vf.Kind()) //typeof(t)= main.T vf.Type= *main.T vf.Kind= ptr ee := vf.Elem() eet := ee.Type() for i := 0; i < ee.NumField(); i ++ { f := ee.Field(i) fmt.Printf("%s %s = %v\n", eet.Field(i).Name, f.Type(), f.Interface()) //A int = 123 } fmt.Printf("%v %v", eet, ee)//main.T {123 hello world} }
Go 依赖注入里用到reflect:
https://github.com/codegangsta/inject
时间: 2024-10-12 03:51:18