接口的两种底层结构体
类型 iface 和 eface 都是 Go 中描述接口的底层结构体,区别在于 iface 描述的接口包含方法,而 eface 描述的则是不包含任何方法的空接口:interface{}。
iface
从源码层面看 iface 结构体:
type iface struct {
tab *itab
data unsafe.Pointer
}
type itab struct {
inter *interfacetype
_type *_type
link *itab
hash uint32 // copy of _type.hash Used for type switches
_ [4] byte
fun [1]uintptr // variable sized
}
结构体 iface 内部维护了两个指针,字段 tab 指向一个 itab 实体,它表示接口的类型以及赋给这个接口的实体类型;字段 data 则指向接口的具体的值,一般是一个指向堆内存的指针。
再仔细看一下 itab 结构体:
- 其中的 _type 字段描述了实体的类型,这是 Go 中各种数据类型的结构体,几乎所有类型的底层结构体都能看到它的身影,它描述了内存对齐的方式、大小等;
- inter 字段则描述了接口的类型;
- fun 字段放置和接口方法对应的具体数据类型的方法地址,实现了接口调用方法的动态派发,一般在每次给接口赋值发生转换时会更新此表。
fun 数组大小为什么只为 1?要是定义了多个方法怎么办呢?
实际上,这里存储的是第一个方法的函数指针,如果有更多的方法,会在它之后的内存空间里继续存储,即这些方法的函数指针是连续存储的,并且是按照函数名称的字典序进行排列的。
再看一下 Interfacetype 类型,它描述的是接口的类型:
type interface struct {
typ _type
pkgpath name
mhdr []imethod
}
可以看到,它也包装了 _type 类型,还包含了一个 mhdr 字段,表示接口所定义的函数列表,pkgpath 记录定义了接口的包名。
iface 结构的全貌:
eface
接着看 eface 的源码:
type eface struct {
_type *_type // 空接口承载的具体值
data unsafe.Pointer // 具体的值
}
相比于 iface,eface 就比较简单了,它只维护了一个 *_type 字段,表示空接口所承载地具体的实体类型,data 描述了具体的值。
看一个例子,比较一下 iface 和 eface:
package main
import "fmt"
type coder interface{
code()
debug()
}
type Gopher struct {
language string
}
func (p Gopher) code() {
fmt.Printf("i am coding %s language\n", p.language)
}
func (p Gopher) debug() {
fmt.Printf("i am debuging %s language\n", p.language)
}
func main() {
x := 200
var any interface{} = x
fmt.Println(any)
g := Gopher{"Go"}
var c coder = g
fmt.Println(c)
}
执行如下命令,打印出汇编语言指令:
go tool compile -S ./src/main.go
可以看到,main 函数中调用了两个函数:
func convT2E64(t *_type, elem unsafe.Pointer) (e eface)
func convT2I(tab *itab, elem unsafe.Pointer) (i iface)
上面两个函数的参数和 iface 和 eface 结构体字段是可以联系起来的:两个函数都是将参数组装一下,形成最终的接口类型。
最后看一下无处不在的 _type 结构体:
type _type struct {
// 类型大小
size uintptr
ptrdata uintptr
// 类型的 hash 值
hash uint32
// 类型的 flag,反射相关
tflag tflag
// 内存对齐相关
align uint8
fieldalign uint8
// 类型编号
kind uint8
equal func(unsafe.Pointer, unsafe.Pointer) bool
// gc 相关
gcdata *byte
str nameOff
ptrTothis typeOff
}
Go 语言各种数据类型都是在 _type 字段基础上,增加一些额外的字段来进行管理的
type arraytype struct {
typ _type
elem *_type
slice *_type
len uintptr
}
type chantype struct{
typ _type
elem *_type
dir uintptr
}
type slicetype struct {
typ _type
elem *_type
}
type structtype struct{
typ _type
pkgPath name
fields []structfiled
}
这些数据类型的结构体定义是反射实现的基础。