1. interface{}初探

Go是强类型语言,各个实例变量的类型信息正是存放在interface{}中的,Go中的反射也与其底层结构有关。

ifaceefaceifaceefaceinterface{}
ifaceeface

2. eface

eface_typedata
dataifaceeface
_typeeface_typeifaceeface_type
sizeptrdatahashtflagalignfieldalign

3. iface

efaceifaceitab_type_typehash_typehashbadinhashfun
interfacetype
fun
itabfunitabfunitab
iface

4. 接口转化

ifaceinterfacetype_typeifaceitabitab

->itable

当判定一种类型是否满足某个接口时,Go 使用类型的方法集和接口所需要的方法集进行匹配,如果类型的方法集完全包含接口的方法集,则可认为该类型实现了该接口。

mnO(mn)O(m+n)

Go的接口实现是非侵入式的,而是鸭子模式:如果某个东西长得像鸭子,像鸭子一样游泳,像鸭子一样嘎嘎叫,那它就可以被看成是一只鸭子。

因此,只要我们实现了接口对应的方法,也就实现了对应的接口,不需要单独申明。