funcmain() { var m manager t := reflect.TypeOf(&m) if t.Kind() == reflect.Ptr { t = t.Elem() }
for i := 0; i < t.NumField(); i++ { f := t.Field(i) fmt.Println(f.Name, f.Type, f.Offset) if f.Anonymous { for x := 0; x < f.Type.NumField(); x++ { af := f.Type.Field(x) fmt.Println(" ", af.Name, af.Type) } } } } /// 输出: /// user main.user 0 /// name string /// age int /// title string 24
对于匿名字段,可用多级索引(按定义顺序)直接访问
1 2 3 4 5 6 7 8 9 10 11 12 13
funcmain() { var m manager t := reflect.TypeOf(m) name, _ := t.FieldByName("name") ///< 按名称查找 fmt.Println(name.Name, name.Type)
age := t.FieldByIndex([]int{0, 1}) ///< 按多级索引查找 fmt.Println(age.Name, age.Type) }
type user struct { name string`field:"name" type:"varchar(50)"` age int`field:"age" type:"int"` }
funcmain() { var u user t := reflect.TypeOf(u) for i := 0; i < t.NumField(); i++ { f := t.Field(i) fmt.Printf("%s: %s %s\n", f.Name, f.Tag.Get("field"), f.Tag.Get("type")) } }
/// 输出: /// name: name varchar(50) /// age: age int
type X struct {} func(X) Format(s string, a ...interface{}) string { return fmt.Sprintf(s, a...) }
funcmain() { var a X v := reflect.ValueOf(&a) m := v.MethodByName("Format") out := m.Call([]reflect.Value{ reflect.ValueOf("%s = %d"), reflect.ValueOf("x"), reflect.ValueOf("100"), })
fmt.Println(out)
out = m.CallSlice([]reflect.ValueP{ reflect.ValueOf("%s = %d"), reflect.ValueOf([]interface{}{"x", 100}), })
var ret reflect.Value switch args[0].Kind() { case reflect.Int: n := 0 for _, a := range args { n += int(a.Int()) }
ret = reflect.ValueOf(n) case reflect.String: ss := make([]string, 0, len(args)) for _, s := range args { ss = append(ss, s.String()) } ret = reflect.ValueOf(strings.Join(ss, "")) } results = append(results, ret) return }