0
点赞
收藏
分享

微信扫一扫

interface实现分析

在runtime包下的runtime2.go文件中
Go使用iface和eface来表达interface。iface其实就是内部有函数的interface

eface表示empty interface,从逻辑上来说,既然空接口没有任何函数,那所有对象就自然都实现了该interface。

空接口
type eface struct {
_type *_type
data unsafe.Pointer
}

type _type struct {
size uintptr
ptrdata uintptr
hash uint32
tflag tflag
align uint8
fieldalign uint8
kind uint8
alg *typeAlg

gcdata    *byte
str nameOff
ptrToThis typeOff

}

非空接口
type iface struct {
tab *itab
data unsafe.Pointer
}

type itab struct {
inter *interfacetype
_type *_type
link *itab
bad int32
unused int32
fun [1]uintptr
}

iface适用场景
在go语言中,借助iface,实现了传统oop编程中DIP(dependency inversion princip),即依赖反转

eface是iface的子集,eface是为了优化

eface 适用场景
func Unmarshal(data []byte, v interface{}) error {}
使用interface主要是我们在不知道用户的输入类型信息的前提下,希望能够实现一些通用的数据结果或函数,将interface{}作为函数的输入/输出参数,泛型的使用场景。

interface实现分析_泛型

interface实现分析_泛型_02
interface实现分析_go语言_03
interface实现分析_go语言_04
interface实现分析_go语言_05


举报

相关推荐

0 条评论