当前位置:网站首页>Go反射—Go语言圣经学习笔记
Go反射—Go语言圣经学习笔记
2022-04-23 04:14:00 【沉淅尘】
Go反射—Go语言圣经学习笔记
Go语言提供了一种反射机制,能够在运行时更新变量和检查它们的值、调用它们的方法和它们支持的内在操作,而不需要在编译时就知道这些变量的具体类型。反射也可以让我们将类型本身作为第一类的值类型处理。
在 go 语言中,实现反射能力的是 reflect包,能够让程序操作不同类型的对象。其中,在反射包中有两个非常重要的 类型和 函数,两个函数分别是:
reflect.TypeOf- 能获取对象的类型的信息reflect.ValueOf- 能获取对象的数据
为何需要反射
有时候我们需要编写一个函数能够处理一类并不满足普通公共接口的类型的值,也可能是因为它们并没有确定的表示方式,或者是在我们设计该函数的时候这些类型可能还不存在。
一个大家熟悉的例子是fmt.Fprintf函数提供的字符串格式化处理逻辑,它可以用来对任意类型的值格式化并打印,甚至支持用户自定义的类型。让我们也来尝试实现一个类似功能的函数。为了简单起见,我们的函数只接收一个参数,然后返回和fmt.Sprint类似的格式化后的字符串。我们实现的函数名也叫Sprint。
我们首先用switch类型分支来测试输入参数是否实现了String方法,如果是的话就调用该方法。然后继续增加类型测试分支,检查这个值的动态类型是否是string、int、bool等基础类型,并在每种情况下执行相应的格式化操作。
func Sprint(x interface{}) string {
type stringer interface {
String() string
}
switch x := x.(type) {
case stringer:
return x.String()
case string:
return x
case int:
return strconv.Itoa(x)
// ...similar cases for int16, uint32, and so on...
case bool:
if x {
return "true"
}
return "false"
default:
// array, chan, func, map, pointer, slice, struct
return "???"
}
}
但是我们如何处理其它类似[]float64、map[string][]string等类型呢?我们当然可以添加更多的测试分支,但是这些组合类型的数目基本是无穷的。还有如何处理类似url.Values这样的具名类型呢?即使类型分支可以识别出底层的基础类型是map[string][]string,但是它并不匹配url.Values类型,因为它们是两种不同的类型,而且switch类型分支也不可能包含每个类似url.Values的类型,这会导致对这些库的依赖。
没有办法来检查未知类型的表示方式,我们被卡住了。这就是我们为何需要反射的原因。
reflect.Type 和 reflect.Value
反射是由 reflect 包提供的。它定义了两个重要的类型,Type 和 Value。一个 Type 表示一个Go类型。它是一个接口,有许多方法来区分类型以及检查它们的组成部分,例如一个结构体的成员或一个函数的参数等。唯一能反映 reflect.Type 实现的是接口的类型描述信息(§7.5),也正是这个实体标识了接口值的动态类型。
函数 reflect.TypeOf 接受任意的 interface{} 类型,并以 reflect.Type 形式返回其动态类型:
t := reflect.TypeOf(3) // a reflect.Type
fmt.Println(t.String()) // "int"
fmt.Println(t) // "int"
其中 TypeOf(3) 调用将值 3 传给 interface{} 参数。回到 7.5节 的将一个具体的值转为接口类型会有一个隐式的接口转换操作,它会创建一个包含两个信息的接口值:操作数的动态类型(这里是 int)和它的动态的值(这里是 3)。
因为 reflect.TypeOf 返回的是一个动态类型的接口值,它总是返回具体的类型。因此,下面的代码将打印 “*os.File” 而不是 “io.Writer”。稍后,我们将看到能够表达接口类型的 reflect.Type。
var w io.Writer = os.Stdout
fmt.Println(reflect.TypeOf(w)) // "*os.File"
要注意的是 reflect.Type 接口是满足 fmt.Stringer 接口的。因为打印一个接口的动态类型对于调试和日志是有帮助的, fmt.Printf 提供了一个缩写 %T 参数,内部使用 reflect.TypeOf 来输出:
fmt.Printf("%T\n", 3) // "int"
reflect 包中另一个重要的类型是 Value。一个 reflect.Value 可以装载任意类型的值。函数 reflect.ValueOf 接受任意的 interface{} 类型,并返回一个装载着其动态值的 reflect.Value。和 reflect.TypeOf 类似,reflect.ValueOf 返回的结果也是具体的类型,但是 reflect.Value 也可以持有一个接口值。
v := reflect.ValueOf(3) // a reflect.Value
fmt.Println(v) // "3"
fmt.Printf("%v\n", v) // "3"
fmt.Println(v.String()) // NOTE: "<int Value>"
和 reflect.Type 类似,reflect.Value 也满足 fmt.Stringer 接口,但是除非 Value 持有的是字符串,否则 String 方法只返回其类型。而使用 fmt 包的 %v 标志参数会对 reflect.Values 特殊处理。
对 Value 调用 Type 方法将返回具体类型所对应的 reflect.Type:
t := v.Type() // a reflect.Type
fmt.Println(t.String()) // "int"
reflect.ValueOf 的逆操作是 reflect.Value.Interface 方法。它返回一个 interface{} 类型,装载着与 reflect.Value 相同的具体值:
v := reflect.ValueOf(3) // a reflect.Value
x := v.Interface() // an interface{}
i := x.(int) // an int
fmt.Printf("%d\n", i) // "3"
reflect.Value 和 interface{} 都能装载任意的值。所不同的是,一个空的接口隐藏了值内部的表示方式和所有方法,因此只有我们知道具体的动态类型才能使用类型断言来访问内部的值(就像上面那样),内部值我们没法访问。相比之下,一个 Value 则有很多方法来检查其内容,无论它的具体类型是什么。让我们再次尝试实现我们的格式化函数 format.Any。
我们使用 reflect.Value 的 Kind 方法来替代之前的类型 switch。虽然还是有无穷多的类型,但是它们的 kinds 类型却是有限的:Bool、String 和 所有数字类型的基础类型;Array 和 Struct 对应的聚合类型;Chan、Func、Ptr、Slice 和 Map 对应的引用类型;interface 类型;还有表示空值的 Invalid 类型。(空的 reflect.Value 的 kind 即为 Invalid。)
gopl.io/ch12/format
package format
import (
"reflect"
"strconv"
)
// Any formats any value as a string.
func Any(value interface{}) string {
return formatAtom(reflect.ValueOf(value))
}
// formatAtom formats a value without inspecting its internal structure.
func formatAtom(v reflect.Value) string {
switch v.Kind() {
case reflect.Invalid:
return "invalid"
case reflect.Int, reflect.Int8, reflect.Int16,
reflect.Int32, reflect.Int64:
return strconv.FormatInt(v.Int(), 10)
case reflect.Uint, reflect.Uint8, reflect.Uint16,
reflect.Uint32, reflect.Uint64, reflect.Uintptr:
return strconv.FormatUint(v.Uint(), 10)
// ...floating-point and complex cases omitted for brevity...
case reflect.Bool:
return strconv.FormatBool(v.Bool())
case reflect.String:
return strconv.Quote(v.String())
case reflect.Chan, reflect.Func, reflect.Ptr, reflect.Slice, reflect.Map:
return v.Type().String() + " 0x" +
strconv.FormatUint(uint64(v.Pointer()), 16)
default: // reflect.Array, reflect.Struct, reflect.Interface
return v.Type().String() + " value"
}
}
到目前为止,我们的函数将每个值视作一个不可分割没有内部结构的物品,因此它叫 formatAtom。对于聚合类型(结构体和数组)和接口,只是打印值的类型,对于引用类型(channels、functions、pointers、slices 和 maps),打印类型和十六进制的引用地址。虽然还不够理想,但是依然是一个重大的进步,并且 Kind 只关心底层表示,format.Any 也支持具名类型。例如:
var x int64 = 1
var d time.Duration = 1 * time.Nanosecond
fmt.Println(format.Any(x)) // "1"
fmt.Println(format.Any(d)) // "1"
fmt.Println(format.Any([]int64{x})) // "[]int64 0x8202b87b0"
fmt.Println(format.Any([]time.Duration{d})) // "[]time.Duration 0x8202b87e0"
版权声明
本文为[沉淅尘]所创,转载请带上原文链接,感谢
https://blog.csdn.net/weixin_41335923/article/details/121222844
边栏推荐
- Understand the gut organ axis, good gut and good health
- 为什么推荐你学嵌入式
- [AI vision · quick review of robot papers today, issue 30] Thu, 14 APR 2022
- 列表、元组、字典和集合的区别
- UDP protocol and TCP protocol
- CRF based medical entity recognition baseline
- [AI vision · quick review of NLP natural language processing papers today, issue 31] Fri, 15 APR 2022
- LabVIEW 小端序和大端序区别
- Man's life
- Express middleware ② (classification of Middleware)
猜你喜欢
![[AI vision · quick review of today's sound acoustic papers, issue 2] Fri, 15 APR 2022](/img/c2/fd9531e48118e384bc5d490ee8e506.png)
[AI vision · quick review of today's sound acoustic papers, issue 2] Fri, 15 APR 2022

HMS Core Discovery第14期回顾长文|纵享丝滑剪辑,释放视频创作力
![[AI vision · quick review of robot papers today, issue 32] wed, 20 APR 2022](/img/eb/916a3fc1a89356fd8e74b943172ac3.png)
[AI vision · quick review of robot papers today, issue 32] wed, 20 APR 2022

Photoshop installation under win10

Matlab reads multiple fig graphs and then combines them into one graph (in the form of sub graph)

Shopping mall for transportation tools based on PHP
![[mapping program design] coordinate azimuth calculation artifact (version C)](/img/2b/e640f3e2702f80d003fa3dd5c4158d.png)
[mapping program design] coordinate azimuth calculation artifact (version C)

VSCode配置之Matlab极简配置

STM32 MCU ADC rule group multi-channel conversion DMA mode

Kotlin. The binary version of its metadata is 1.6.0, expected version is 1.1.15.
随机推荐
Overview of knowledge map (II)
减治思想——二分查找详细总结
伦敦银最新价格走势图与买卖点
Who will answer the question?
IEEE Transactions on Systems, Man, and Cybernetics: Systems(TSMC)投稿须知
Xshell、Xftp连接新创建的Unbutu系统虚拟机全流程
【BIM入门实战】Revit建筑墙体:构造、包络、叠层图文详解
C语言 字符常量
优麒麟 22.04 LTS 版本正式发布 | UKUI 3.1开启全新体验
为什么推荐你学嵌入式
As a code farmer, what kind of experience is it that a girlfriend can code better than herself?
无线充电全国产化电子元件推荐方案
洛谷P1858 【多人背包】 (背包求前k优解)
Counting and sorting (C language implementation) -- learning notes
国外LEAD,联盟经理常见问答
Nel ASA: her ø Ya facility in Norway officially opened
Difference between LabVIEW small end sequence and large end sequence
Machine translation baseline
[string] ranking of country names ----- problem solving notes
OpenCV----YOLACT实例分割模型推理