reflect包连缀


姊妹篇:

反射

Golang类型断言


1.reflect.TypeOf(argument).Kind() == reflect.String

有一个interface{}类型的切片,输出其中所有string类型的值及其索引

1
2
3
4
5
6
sli := []interface{}{"1213", 3456, 7867, "hao", "city"}
for argNum, arg := range sli {
if reflect.TypeOf(arg).Kind() == reflect.String {
fmt.Printf("第%d个元素%s为string类型\n",argNum,arg)
}
}

输出为:

1
2
3
0个元素1213为string类型
3个元素hao为string类型
4个元素city为string类型

如果直接reflect.TypeOf(arg).Kind() == "string",则会报错

1
mismatched type Kind and string

这么直接粗暴地写是不行滴~




参考:

深入Go语言 - 13

Go Reflect 性能




源码剖析


Golang 反射应用及源码分析


example_test.go中的几个测试用例:

  • ExampleKind: 实现简单的类型判断

  • ExampleMakeFunc: 传入任意类型的两个参数,实现这两个参数之间的交换

  • ExampleStructTag:读取结构体定义的tag信息

  • ExampleStructTag_Lookup:tag的查找

  • ExampleTypeOf: 判断一个结构体是否实现了某个接口

  • ExampleStructOf:


两个slice(或map/struct)直接比较是不被允许的, 使用DeepEqual可以比较,如果元素一一对应,则为true


函数调用

https://github.com/KippaZou/learn-reflection/blob/main/function_call.go


一些用到反射的包


proto reflect

sqlx scanAll

testify


反射三大定律


The Laws of Reflection

  • Reflection goes from interface value to reflection object.
  • Reflection goes from reflection object to interface value.
  • To modify a reflection object, the value must be settable.

whimsical


benchmark


reflect benchmark


reflect 阅读材料

反射