多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
[TOC] ## reflect ### type 所有的类型 ``` const ( Invalid Kind = iota Bool Int Int8 Int16 Int32 Int64 Uint Uint8 Uint16 Uint32 Uint64 Uintptr Float32 Float64 Complex64 Complex128 Array Chan Func Interface Map Ptr Slice String Struct UnsafePointer ) ``` ### reflect.ValueOf ``` type Value func ValueOf(i interface{}) Value func Zero(typ Type) Value func New(typ Type) Value func NewAt(typ Type, p unsafe.Pointer) Value func Indirect(v Value) Value func MakeSlice(typ Type, len, cap int) Value func MakeMap(typ Type) Value func MakeChan(typ Type, buffer int) Value func MakeFunc(typ Type, fn func(args []Value) (results []Value)) Value func Append(s Value, x ...Value) Value func AppendSlice(s, t Value) Value func (v Value) IsValid() bool func (v Value) IsNil() bool func (v Value) Kind() Kind func (v Value) Type() Type func (v Value) Convert(t Type) Value func (v Value) Elem() Value func (v Value) Bool() bool func (v Value) Int() int64 func (v Value) OverflowInt(x int64) bool func (v Value) Uint() uint64 func (v Value) OverflowUint(x uint64) bool func (v Value) Float() float64 func (v Value) OverflowFloat(x float64) bool func (v Value) Complex() complex128 func (v Value) OverflowComplex(x complex128) bool func (v Value) Bytes() []byte func (v Value) String() string func (v Value) Pointer() uintptr func (v Value) InterfaceData() [2]uintptr func (v Value) Slice(i, j int) Value func (v Value) Slice3(i, j, k int) Value func (v Value) Cap() int func (v Value) Len() int func (v Value) Index(i int) Value func (v Value) MapIndex(key Value) Value func (v Value) MapKeys() []Value func (v Value) NumField() int func (v Value) Field(i int) Value func (v Value) FieldByIndex(index []int) Value func (v Value) FieldByName(name string) Value func (v Value) FieldByNameFunc(match func(string) bool) Value func (v Value) Recv() (x Value, ok bool) func (v Value) TryRecv() (x Value, ok bool) func (v Value) Send(x Value) func (v Value) TrySend(x Value) bool func (v Value) Close() func (v Value) Call(in []Value) []Value func (v Value) CallSlice(in []Value) []Value func (v Value) NumMethod() int func (v Value) Method(i int) Value func (v Value) MethodByName(name string) Value func (v Value) CanAddr() bool func (v Value) Addr() Value func (v Value) UnsafeAddr() uintptr func (v Value) CanInterface() bool func (v Value) Interface() (i interface{}) func (v Value) CanSet() bool func (v Value) SetBool(x bool) func (v Value) SetInt(x int64) func (v Value) SetUint(x uint64) func (v Value) SetFloat(x float64) func (v Value) SetComplex(x complex128) func (v Value) SetBytes(x []byte) func (v Value) SetString(x string) func (v Value) SetPointer(x unsafe.Pointer) func (v Value) SetCap(n int) func (v Value) SetLen(n int) func (v Value) SetMapIndex(key, val Value) func (v Value) Set(x Value) ``` ### Type ``` type Type func ArrayOf(count int, elem Type) Type func ChanOf(dir ChanDir, t Type) Type func FuncOf(in, out []Type, variadic bool) Type func MapOf(key, elem Type) Type func PtrTo(t Type) Type func SliceOf(t Type) Type func StructOf(fields []StructField) Type func TypeOf(i interface{}) Type ``` ## 实例 ### reflect.ValueOf 查看反射类型 ``` for _, v := range []interface{}{"hi", 42, func() {}} { switch v := reflect.ValueOf(v); v.Kind() { case reflect.String: fmt.Println(v.String()) case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: fmt.Println(v.Int()) default: fmt.Printf("unhandled kind %s", v.Kind()) } } // Output: // hi // 42 // unhandled kind func ``` ### reflect.TypeOf 查看tag 标签 ``` type S struct { F string `species:"gopher" color:"blue"` } var s S of := reflect.TypeOf(s) fmt.Printf("%+v\n", of.Field(0).Tag.Get("species")) // gopher fmt.Printf("%+v\n", of.Field(0).Tag.Get("color")) // blue ``` ### Elem 当传入指针时,获取类型 ``` func main() { type Admin struct { username string `demo:"user" type:"name"` title string } a:=Admin{ username: "123", title: "22", } demo1(a) demo2(&a) } func demo1(i interface{}) { of := reflect.ValueOf(i) fmt.Printf("%+v\n", of.Field(0).String()) } func demo2(i interface{}) { of := reflect.ValueOf(i).Elem() fmt.Printf("%+v\n", of.Field(0).String()) } ``` ### Set 赋值 ``` type T struct { Age int Name string Children []int } // 初始化测试用例 t := T{12, "someone-life", nil} //var t T s := reflect.ValueOf(&t).Elem() // 反射获取测试对象对应的struct枚举类型fmt.Println(s.NumField()) //3 log.Printf("%v",s.NumField()) //3 s.Field(1).SetString("ccc") s.FieldByName("Age").SetInt(123) sliceValue := reflect.ValueOf([]int{1, 2, 3}) s.FieldByName("Children").Set(sliceValue) // 使用字段名称get,并赋值。赋值类型必须为reflect.Value fmt.Printf("%+v\n", s) //{Age:123 Name:ccc Children:[1 2 3]} ``` ### MakeFunc 泛型函数 ``` var intSwap func(int, int) (int, int) var floatSwap func(float64, float64) (float64, float64) var swap = func(in []reflect.Value) []reflect.Value { return []reflect.Value{in[1], in[0]} } func makeSwap(fptr interface{}) { fn := reflect.ValueOf(fptr).Elem() v := reflect.MakeFunc(fn.Type(), swap) fn.Set(v) } func init() { makeSwap(&intSwap) makeSwap(&floatSwap) } func main() { fmt.Println(intSwap(0, 1)) // 1 0 fmt.Println(floatSwap(2.72, 3.14)) // 3.14 2.72 } ``` ### reflect.DeepEqua` 可比较连个 interface 是否相等 ``` equal := reflect.DeepEqual([]string{"13"}, []string{"123"}) ```