Go的interface源码在Golang源码的runtime目录中。
Go在不同版本之间的interface结构可能会有所不同,但是,整体的结构是不会改变的,此文章用的Go版本是1.11。
Go的interface是由两种类型来实现的:iface和eface。
其中,iface表示的是包含方法的interface,例如:
type Person interface {
Print()
}
而eface代表的是不包含方法的interface,即
type Person interface {}
或者
var person interface{} = xxxx实体
eface
eface的具体结构是:
_type_type_typedata
type
type _type struct {
size uintptr
ptrdata uintptr // size of memory prefix holding all pointers
hash uint32
tflag tflag
align uint8
fieldalign uint8
kind uint8
alg *typeAlg
// gcdata stores the GC type data for the garbage collector.
// If the KindGCProg bit is set in kind, gcdata is a GC program.
// Otherwise it is a ptrmask bitmap. See mbitmap.go for details.
gcdata *byte
str nameOff
ptrToThis typeOff
}
eface
对于没有方法的interface赋值后的内部结构是怎样的呢?
可以先看段代码:
import (
"fmt"
"strconv"
)
type Binary uint64
func main() {
b := Binary(200)
any := (interface{})(b)
fmt.Println(any)
}
输出200,赋值后的结构图是这样的:
typeconvT2Eruntimeiface
iface
type Person interface {
Print()
}
iface
type iface struct {
tab *itab
data unsafe.Pointer
}
iface
itabifaceeface
itab
type itab struct {
inter *interfacetype //此属性用于定位到具体interface
_type *_type //此属性用于定位到具体interface
hash uint32 // copy of _type.hash. Used for type switches.
_ [4]byte
fun [1]uintptr // variable sized. fun[0]==0 means _type does not implement inter.
}
interfacetype_typemaptypearraytypechantypeinterfacetype
type interfacetype struct {
typ _type
pkgpath name
mhdr []imethod
}
type imethod struct {
name nameOff
ityp typeOff
}
iface
对于含有方法的interface赋值后的内部结构是怎样的呢?
一下代码运行后
package main
import (
"fmt"
"strconv"
)
type Binary uint64
func (i Binary) String() string {
return strconv.FormatUint(i.Get(), 10)
}
func (i Binary) Get() uint64 {
return uint64(i)
}
func main() {
b := Binary(200)
any := fmt.Stringer(b)
fmt.Println(any)
}
fmt.StringerString
type Stringer interface {
String() string
}
Stringer
type(Binary)convT2Iruntime