Go Reflect 高级实践

65次阅读

共计 4607 个字符,预计需要花费 12 分钟才能阅读完成。

https://golang.org/pkg/reflect/ 最重要的官方文档,建议先粗读一遍再来看本文。
go 的 reflect 还是比较简单的,可以很快上手。

https://github.com/golang/go/blob/master/src/reflect/type.go https://github.com/golang/go/blob/master/src/reflect/value.go 源码中有上百个 panic,各种检查做的很全面,有想法就大胆地去试,只要能 run 起来,一般问题不大。
实际使用中可以先不考虑使用 reflect 对性能的影响,先实现功能,再利用 benchmark test 去优化

什么时候应该用 reflect

为了降低多写代码造成的 bug 率,做更好的规约和抽象。
为了灵活、好用、方便,做动态解析、调用和处理。
为了代码好看、易读、提高开发效率,补足与动态语言之间的一些差别

记住!reflect 不是用来实现你的奇技淫巧的!使用 reflect 要适可而止!
reflect 核心
TypeOf(i interface{}) Type
重点看这个返回值,它是一个接口,主要实现它的是 struct rtype,这个也是 go 类型系统的核心,和 runtime/type.go struct _type 一致,这里就不深入展开了,回头再说。
type Type interface {
// 变量的内存对齐,返回 rtype.align
Align() int

// struct 字段的内存对齐,返回 rtype.fieldAlign
FieldAlign() int

// 根据传入的 i,返回方法实例,表示类型的第 i 个方法
Method(int) Method

// 根据名字返回方法实例,这个比较常用
MethodByName(string) (Method, bool)

// 返回类型方法集中可导出的方法的数量
NumMethod() int

// 只返回类型名,不含包名
Name() string

// 返回导入路径,即 import 路径
PkgPath() string

// 返回 rtype.size 即类型大小,单位是字节数
Size() uintptr

// 返回类型名字,实际就是 PkgPath() + Name()
String() string

// 返回 rtype.kind,描述一种基础类型
Kind() Kind

// 检查当前类型有没有实现接口 u
Implements(u Type) bool

// 检查当前类型能不能赋值给接口 u
AssignableTo(u Type) bool

// 检查当前类型能不能转换成接口 u 类型
ConvertibleTo(u Type) bool

// 检查当前类型能不能做比较运算,其实就是看这个类型底层有没有绑定 typeAlg 的 equal 方法。打住!不要去搜 typeAlg 是什么,不然你会陷进去的!先把本文看完。
Comparable() bool

// 返回类型的位大小,但不是所有类型都能调这个方法,不能调的会 panic
Bits() int

// 返回 channel 类型的方向,如果不是 channel,会 panic
ChanDir() ChanDir

// 返回函数类型的最后一个参数是不是可变数量的,”…” 就这样的,同样,如果不是函数类型,会 panic
IsVariadic() bool

// 返回所包含元素的类型,只有 Array, Chan, Map, Ptr, Slice 这些才能调,其他类型会 panic,这不是废话吗。。其他类型也没有包含元素一说。
Elem() Type

// 返回 struct 类型的第 i 个字段,不是 struct 会 panic,i 越界也会 panic
Field(i int) StructField

// 跟上边一样,不过是嵌套调用的,比如 [1, 2] 就是说返回当前 struct 的第 1 个 struct 的第 2 个字段,适用于 struct 本身嵌套的类型
FieldByIndex(index []int) StructField

// 按名字找 struct 字段,第二个返回值 ok 表示有没有
FieldByName(name string) (StructField, bool)

// 按函数名找 struct 字段,因为 struct 里也可能有类型是 func 的嘛
FieldByNameFunc(match func(string) bool) (StructField, bool)

// 返回函数第 i 个参数的类型,不是 func 会 panic
In(i int) Type

// 返回 map 的 key 的类型,不是 map 会 panic
Key() Type

// 返回 array 的长度,不是 array 会 panic
Len() int

// 返回 struct 字段数量,不是 struct 会 panic
NumField() int

// 返回函数的参数数量,不是 func 会 panic
NumIn() int

// 返回函数的返回值数量,不是 func 会 panic
NumOut() int

// 返回函数第 i 个返回值的类型,不是 func 会 panic
Out(i int) Type
}
ValueOf(i interface{}) Value
先看看定义吧,就这么点东西。
type Value struct {
// 反射出来此值的类型,rtype 是啥往上看,但可别弄错了,这 typ 是未导出的,从外部调不到 Type 接口的方法
typ *rtype

// 数据形式的指针值
ptr unsafe.Pointer

// 保存元数据
flag
}

Value 的方法太多了,参考开头的官方文档吧,我下面挑几个重点的说一下,像 len,cap 这种简单的就不介绍了:
// 前提 v 是一个 func,然后调用 v,并传入 in 参数,第一个参数是 in[0],第二个是 in[1],以此类推
func (v Value) Call(in []Value) []Value

// 返回 v 的接口值或者指针
func (v Value) Elem() Value

// 前提 v 是一个 struct,返回第 i 个字段,这个主要用于遍历
func (v Value) Field(i int) Value

// 前提 v 是一个 struct,根据字段名直接定位返回
func (v Value) FieldByName(name string) Value

// 前提 v 是 Array, Slice, String 之一,返回第 i 个元素,主要也是用于遍历,注意不能越界
func (v Value) Index(i int) Value

// 判断 v 是不是 nil,只有 chan, func, interface, map, pointer, slice 可以用,其他类型会 panic
func (v Value) IsNil() bool

// 判断 v 是否合法,如果返回 false,那么除了 String() 以外的其他方法调用都会 panic,事前检查是必要的
func (v Value) IsValid() bool

// 前提 v 是个 map,返回对应 value
func (v Value) MapIndex(key Value)

// 前提 v 是个 map,返回所有 key 组成的一个 slice
func (v Value) MapKeys() []Value

// 前提 v 是个 struct,返回字段个数
func (v Value) NumField() int

// 赋值
func (v Value) Set(x Value)

// 类型
func (v Value) Type() Type
reflect 场景实践
动态调用函数(无参数)
type T struct {}

func main() {
name := “Do”
t := &T{}
reflect.ValueOf(t).MethodByName(name).Call(nil)
}

func (t *T) Do() {
fmt.Println(“hello”)
}
动态调用函数(有参数)
type T struct{}

func main() {
name := “Do”
t := &T{}
a := reflect.ValueOf(1111)
b := reflect.ValueOf(“world”)
in := []reflect.Value{a, b}
reflect.ValueOf(t).MethodByName(name).Call(in)
}

func (t *T) Do(a int, b string) {
fmt.Println(“hello” + b, a)
}
处理返回值中的错误
返回值也是 Value 类型,对于错误,可以转为 interface 之后断言
type T struct{}

func main() {
name := “Do”
t := &T{}
ret := reflect.ValueOf(t).MethodByName(name).Call(nil)
fmt.Printf(“strValue: %[1]vnerrValue: %[2]vnstrType: %[1]TnerrType: %[2]T”, ret[0], ret[1].Interface().(error))
}

func (t *T) Do() (string, error) {
return “hello”, errors.New(“new error”)
}

struct tag 解析
type T struct {
A int `json:”aaa” test:”testaaa”`
B string `json:”bbb” test:”testbbb”`
}

func main() {
t := T{
A: 123,
B: “hello”,
}
tt := reflect.TypeOf(t)
for i := 0; i < tt.NumField(); i++ {
field := tt.Field(i)
if json, ok := field.Tag.Lookup(“json”); ok {
fmt.Println(json)
}
test := field.Tag.Get(“test”)
fmt.Println(test)
}
}
类型转换和赋值
type T struct {
A int `newT:”AA”`
B string `newT:”BB”`
}

type newT struct {
AA int
BB string
}

func main() {
t := T{
A: 123,
B: “hello”,
}
tt := reflect.TypeOf(t)
tv := reflect.ValueOf(t)

newT := &newT{}
newTValue := reflect.ValueOf(newT)

for i := 0; i < tt.NumField(); i++ {
field := tt.Field(i)
newTTag := field.Tag.Get(“newT”)
tValue := tv.Field(i)
newTValue.Elem().FieldByName(newTTag).Set(tValue)
}

fmt.Println(newT)
}
通过 kind()处理不同分支
func main() {
a := 1
t := reflect.TypeOf(a)
switch t.Kind() {
case reflect.Int:
fmt.Println(“int”)
case reflect.String:
fmt.Println(“string”)
}
}
判断实例是否实现了某接口
type IT interface {
test1()
}

type T struct {
A string
}

func (t *T) test1() {}

func main() {
t := &T{}
ITF := reflect.TypeOf((*IT)(nil)).Elem()
tv := reflect.TypeOf(t)
fmt.Println(tv.Implements(ITF))
}
未完待续

正文完
 0