二、Go语言Interface
在理解了如何使用Go语言的interface之后,了解其内部实现,有助于我们更好的使用这套机制。
iface和eface都是实现Go语言interface底层的两个结构体。区别在iface描述的是包含方法的接口,而eface则是不包含任何方法的空接口:intrerface{}。
eface
先从较简单的eface看起,空接口eface结构体比较简单, 由两个属性构成,一个是类型信息_type,一个是数据信息data,其结构体声明如下:
type eface struct {_type *_typedata unsafe.Pointer}
_type字段描述了空接口所承载实例的类型,data字段描述了实例的值。
其中_type是GO语言中所有类型的公共描述,Go语言几乎所有的数据结构都可以抽象成 _type,是所有类型的公共描述,type负责决定data应该如何解释和操作,type的结构代码如下:
type _type struct {// 类型大小size uintptrptrdata uintptr// 类型的 hash 值hash uint32// 类型的 flag,和反射相关tflag tflag// 内存对齐相关align uint8fieldalign uint8// 类型的编号,有bool, slice, struct 等等等等kind uint8alg *typeAlg// gc 相关gcdata *bytestr nameOffptrToThis typeOff}
Go 语言各种数据类型都是在 _type 字段的基础上,增加一些额外的字段来进行管理的:
type arraytype struct {typ _typeelem *_typeslice *_typelen uintptr}type chantype struct {typ _typeelem *_typedir uintptr}type slicetype struct {typ _typeelem *_type}type structtype struct {typ _typepkgPath namefields []structfield}
这些数据类型的结构体定义,是反射实现的基础。
https://zhuanlan.zhihu.com/p/76354559
https://zhuanlan.zhihu.com/p/64884660
