GoLang中的iface?和?eface?的區(qū)別解析
GoLang之iface 和 eface 的區(qū)別是什么?
iface和eface都是 Go 中描述接口的底層結構體,區(qū)別在于iface描述的接口包含方法,而eface則是不包含任何方法的空接口:interface{}。
從源碼層面看一下:
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.
bad bool // type does not implement interface
inhash bool // has this itab been added to hash?
unused [2]byte
fun [1]uintptr // variable sized
}
iface內部維護兩個指針,tab指向一個itab實體, 它表示接口的類型以及賦給這個接口的實體類型。data則指向接口具體的值,一般而言是一個指向堆內存的指針。
再來仔細看一下 itab 結構體:_type 字段描述了實體的類型,包括內存對齊方式,大小等;inter 字段則描述了接口的類型。fun 字段放置和接口方法對應的具體數據類型的方法地址,實現接口調用方法的動態(tài)分派,一般在每次給接口賦值發(fā)生轉換時會更新此表,或者直接拿緩存的 itab。
這里只會列出實體類型和接口相關的方法,實體類型的其他方法并不會出現在這里。如果你學過 C++ 的話,這里可以類比虛函數的概念。
另外,你可能會覺得奇怪,為什么 fun 數組的大小為 1,要是接口定義了多個方法可怎么辦?實際上,這里存儲的是第一個方法的函數指針,如果有更多的方法,在它之后的內存空間里繼續(xù)存儲。從匯編角度來看,通過增加地址就能獲取到這些函數指針,沒什么影響。順便提一句,這些方法是按照函數名稱的字典序進行排列的。
再看一下
interfacetype類型,它描述的是接口的類型:
type interfacetype struct {
typ _type
pkgpath name
mhdr []imethod
}
可以看到,它包裝了
_type類型,_type實際上是描述 Go 語言中各種數據類型的結構體。我們注意到,這里還包含一個mhdr字段,表示接口所定義的函數列表,pkgpath記錄定義了接口的包名。
這里通過一張圖來看下
iface結構體的全貌:

接著來看一下
eface的源碼:
type eface struct {
_type *_type
data unsafe.Pointer
}
相比
iface,eface就比較簡單了。只維護了一個_type字段,表示空接口所承載的具體的實體類型。data描述了具體的值。

我們來看個例子:
package main
import "fmt"
func main() {
x := 200
var any interface{} = x
fmt.Println(any)
g := Gopher{"Go"}
var c coder = g
fmt.Println(c)
}
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)
}
執(zhí)行命令,打印出匯編語言:
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
// 類型的編號,有bool, slice, struct 等等等等
kind uint8
alg *typeAlg
// 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 []structfield
}
這些數據類型的結構體定義,是反射實現的基礎。
到此這篇關于GoLang之iface 和 eface 的區(qū)別是什么的文章就介紹到這了,更多相關GoLang iface 和 eface區(qū)別內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
windows下使用vscode搭建golang環(huán)境并調試的過程
這篇文章主要介紹了在windows下使用vscode搭建golang環(huán)境并進行調試,主要包括安裝方法及環(huán)境變量配置技巧,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-09-09

