golang 源码学习之interface

源码目录 //runtime/runtime2.go。 (go 1.12.7)
interface分为两类:iface和eface。eface不带方法,iface带方法。可以说所有的类型都属于eface。iface可以转换成eface,而eface不一定能转换成iface。

数据结构

/// runtime/runtime2.go
type iface struct {
    tab  *itab
    data unsafe.Pointer
}

type eface struct {
    _type *_type
    data  unsafe.Pointer
}

iface和eface的结构都很简单。data指向数据值,区别在于tab和_type。我们先看看tab。

itab

type itab struct {
    inter *interfacetype  // interface类型
    _type *_type   // 真正的类型
    hash  uint32 // copy of _type.hash. Used for type switches.
    _     [4]byte
    fun   [1]uintptr // 接口实现的方法列表。长度不固定,如果为空则说明没有实现interfece的方法
}


type interfacetype struct {
    typ     _type  // interface的类型
    pkgpath name   // 包路径
    mhdr    []imethod  // interface定义的方法
}

type imethod struct {
    name nameOff  // 方法名
    ityp typeOff
}

在上面出现了_type,这里_type是go所有类型的公共描述,类似的还有maptype、arraytype、slicetype...这些都是由 _type 加上 自身特有的描述组成。比如ptrType:

type ptrtype struct {
    typ  _type
    elem *_type // 指针指向元素的类型
}

_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   // 这个也是类型,和reflect/type.go的26个常量对应
    alg        *typeAlg
    gcdata    *byte
    str       nameOff
    ptrToThis typeOff
}
结构
对于eface比较简单,实际类型 + 数据地址

eface和iface比较起来,其实就差了接口类型和实现接口方法列表。

转换(赋值)

iface.go 提供了各种类型转换,convT2E(转换成eface) 、convT2I(转换成iface)、convT32、convT64 ......
/// runtime/iface.go

func convT2E(t *_type, elem unsafe.Pointer) (e eface) {
    if raceenabled {
        raceReadObjectPC(t, elem, getcallerpc(), funcPC(convT2E))
    }
    if msanenabled {
        msanread(elem, t.size)
    }
    x := mallocgc(t.size, t, true) // 内存申请
    typedmemmove(t, x, elem) // 值拷贝
    e._type = t
    e.data = x
    return
}

func convT2I(tab *itab, elem unsafe.Pointer) (i iface) {
    t := tab._type
    if raceenabled {
        raceReadObjectPC(t, elem, getcallerpc(), funcPC(convT2I))
    }
    if msanenabled {
        msanread(elem, t.size)
    }
    x := mallocgc(t.size, t, true)  // 内存申请
    typedmemmove(t, x, elem) // 值拷贝
    i.tab = tab
    i.data = x
    return
}

func convT16(val uint16) (x unsafe.Pointer) {
    if val == 0 {
        x = unsafe.Pointer(&zeroVal[0])
    } else {
        x = mallocgc(2, uint16Type, false) // 内存申请
        *(*uint16)(x) = val // 新内存赋值
    }
    return
}


不管是convT2E还是convT2I data都是值复制。对于uint16 、uint32之类的比较简单,不涉及到itab、_type、data,直接申请内存 拷贝值。对于iface转iface则相对比较复杂,涉及到itab的查询、计算

// inter是要转换成的类型,i是原值
func convI2I(inter *interfacetype, i iface) (r iface) {
    tab := i.tab
    if tab == nil {
        return
    }
    if tab.inter == inter { //如果两iface实现的接口一样, 则直接赋值完事
        r.tab = tab
        r.data = i.data
        return
    }
    r.tab = getitab(inter, tab._type, false) // 获取itab
    r.data = i.data //设置data
    return
}


// itab获取
func getitab(inter *interfacetype, typ *_type, canfail bool) *itab {
    if len(inter.mhdr) == 0 { // interface没有定义方法,说明不是一个iface
        throw("internal error - misuse of itab")
    }

    // easy case
    if typ.tflag&tflagUncommon == 0 {
        if canfail {
            return nil
        }
        name := inter.typ.nameOff(inter.mhdr[0].name)
        panic(&TypeAssertionError{nil, typ, &inter.typ, name.name()})
    }

    var m *itab

    // itabTable是一个全局存itab的变量
    t := (*itabTableType)(atomic.Loadp(unsafe.Pointer(&itabTable)))
    if m = t.find(inter, typ); m != nil { // 如果在itabTable找到itab,进入finish
        goto finish
    }

    // 如果没找到就加锁再找一遍。why? 因为itabTable有可能被其他goroutine修改,所以加锁再查一遍
    lock(&itabLock)
    if m = itabTable.find(inter, typ); m != nil {
        unlock(&itabLock)
        goto finish
    }

    // 如果在itabTable中没找到,则生成一个itab并加入到itabTable中
    m = (*itab)(persistentalloc(unsafe.Sizeof(itab{})+uintptr(len(inter.mhdr)-1)*sys.PtrSize, 0, &memstats.other_sys))
    m.inter = inter
    m._type = typ
    m.init()
    itabAdd(m)
    unlock(&itabLock)
finish:
    if m.fun[0] != 0 { // != 0说明实现了接口
        return m
    }
    
    // canfail = false 返回nil, 否则获取itab失败 恐慌
    if canfail {
        return nil
    }

    panic(&TypeAssertionError{concrete: typ, asserted: &inter.typ, missingMethod: m.init()})
}

func itabAdd(m *itab) {

    if getg().m.mallocing != 0 {
        throw("malloc deadlock")
    }

    t := itabTable
    if t.count >= 3*(t.size/4) { // 超过容量的75%

        t2 := (*itabTableType)(mallocgc((2+2*t.size)*sys.PtrSize, nil, true))
        t2.size = t.size * 2 // 2倍扩容

        iterate_itabs(t2.add) // entries复制
        if t2.count != t.count {
            throw("mismatched count during itab table copy")
        }
        // Publish new hash table. Use an atomic write: see comment in getitab.
        atomicstorep(unsafe.Pointer(&itabTable), unsafe.Pointer(t2))
        // Adopt the new table as our own.
        t = itabTable
        // Note: the old table can be GC'ed here.
    }
    t.add(m)
}

type itabTableType struct {
    size    uintptr             // 数组长度
    count   uintptr             // 已填充个数
    entries [itabInitSize]*itab // itab数组
}

接口转接口:如果实现的接口一样,这简单复制tab和data。否则从全局变量itabTable获取itab,如果itabTable中找不到则新生产itab并加入itabTable,itabTable容量超过75%则两倍扩容。

断言

iface.go 提供了iface转iface (assertI2I、assertI2I2)和 eface转iface(assertE2I、assertE2I2)

func assertI2I(inter *interfacetype, i iface) (r iface) {
    tab := i.tab
    if tab == nil {
        // explicit conversions require non-nil interface value.
        panic(&TypeAssertionError{nil, nil, &inter.typ, ""})
    }
    if tab.inter == inter {
        r.tab = tab
        r.data = i.data
        return
    }
    r.tab = getitab(inter, tab._type, false) // false,当获取不到itab会恐慌
    r.data = i.data
    return
}

func assertI2I2(inter *interfacetype, i iface) (r iface, b bool) {
    tab := i.tab
    if tab == nil {
        return
    }
    if tab.inter != inter {
        tab = getitab(inter, tab._type, true)// true,当获取不到itab会返回nil
        if tab == nil {
            return
        }
    }
    r.tab = tab
    r.data = i.data
    b = true
    return
}

断言和转换几乎一样。断言是否返回bool区别:不返回bool,获取itab失败则恐慌,返回bool,获取itab失败返回false。

后记

以前我觉得一个优秀的程序员需要懂操作系统,现在我觉得还需加一条,需要懂汇编。不然很多东西只能看得是懂非懂。然而我两者都不会 >_<

你可能感兴趣的:(golang 源码学习之interface)