姊妹篇:
1.reflect.TypeOf(argument).Kind() == reflect.String
有一个interface{}类型的切片,输出其中所有string类型的值及其索引
1 | sli := []interface{}{"1213", 3456, 7867, "hao", "city"} |
输出为:
1 | 第0个元素1213为string类型 |
如果直接reflect.TypeOf(arg).Kind() == "string",则会报错
1 | mismatched type Kind and string |
这么直接粗暴地写是不行滴~
参考:
源码剖析
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
一些用到反射的包
反射三大定律
- 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.
benchmark
原文链接: https://dashen.tech/2019/03/26/reflect包连缀/
版权声明: 转载请注明出处.