funcmain() { var a *float32// 指针。 reflectType(a) // name: kind:ptr var b myInt // 自定义类型。 reflectType(b) // name:myInt kind:int64 var c rune// 类型别名。 reflectType(c) // name:int32 kind:int32 var d = person{ name: "Test", age: 18, } reflectType(d) // name:person kind:struct var e = book{title: "BookName"} reflectType(e) // name:book kind:struct }
funcreflectValue(x interface{}) { v := reflect.ValueOf(x) k := v.Kind() switch k { case reflect.Int64: // v.Int()从反射中获取整型的原始值,然后通过int64()强制类型转换。 fmt.Printf("type is int64, value is %d\n", int64(v.Int())) case reflect.Float32: // v.Float()从反射中获取浮点型的原始值,然后通过float32()强制类型转换。 fmt.Printf("type is float32, value is %f\n", float32(v.Float())) case reflect.Float64: // v.Float()从反射中获取浮点型的原始值,然后通过float64()强制类型转换。 fmt.Printf("type is float64, value is %f\n", float64(v.Float())) } } funcmain() { var a float32 = 3.14 var b int64 = 100 reflectValue(a) // type is float32, value is 3.140000 reflectValue(b) // type is int64, value is 100 // 将int类型的原始值转换为reflect.Value类型。 c := reflect.ValueOf(10) fmt.Printf("type c :%T\n", c) // type c :reflect.Value }
type StructField struct { Name string// Name 是字段的名字。 PkgPath string//PkgPath 是非导出字段的包路径,对导出字段该字段为"" Type Type // 字段的类型。 Tag StructTag // 字段的标签。 Offset uintptr// 字段在结构体中的字节偏移量。 Index []int// 用于 Type. FieldByIndex 时的索引切片。 Anonymous bool// 是否匿名字段。 }
t := reflect.TypeOf (stu 1) fmt.Println (t.Name (), t.Kind ()) // student struct // 通过 for 循环遍历结构体的所有字段信息。 for i := 0; i < t.NumField (); i++ { field := t.Field (i) fmt.Printf ("name:%s index:%d type:%v json tag:%v\n", field. Name, field. Index, field. Type, field.Tag.Get ("json")) }
// 通过字段名获取指定结构体字段信息。 if scoreField, ok := t.FieldByName ("Score"); ok { fmt.Printf ("name:%s index:%d type:%v json tag:%v\n", scoreField. Name, scoreField. Index, scoreField. Type, scoreField.Tag.Get ("json")) } }
Method 类型
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
type Method struct { // Name is the method name. Name string
// PkgPath is the package path that qualifies a lower case (unexported) // method name. It is empty for upper case (exported) method names. // The combination of PkgPath and Name uniquely identifies a method // in a method set. // See https://golang.org/ref/spec#Uniqueness_of_identifiers PkgPath string
Type Type // method type Func Value // func with receiver as first argument Index int// index for Type. Method }