Go 原理-详解 interface

golang的interface接口,表示一组方法集合;实现方法的实例可以存储在接口类型的变量;有一种特殊的接口类型就是空接口类型interface{},对于带有方法的接口类型和不带任何方法的 interface{} 类型,底层实现是不一样的。

  空interface{}的底层实现是eface

type eface struct { // 16 bytes
    _type *_type   //指向底层类型
    data  unsafe.Pointer //指向底层数据(具体值)
}

  带有方法集合的接口底层实现iface

type iface struct { // 16 bytes
    tab  *itab  //指向下边的结构,出来底层类型外 还包含其他信息
    data unsafe.Pointer //指向底层数据(具体值)
}

  

type itab struct { // 32 bytes
    inter *interfacetype  //接口类型描述
    _type *_type  //底层类型
    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. //是一个指针数组,每个指针指向具体类型 _type 实现的具体方法
}

  

posted @ 2020-10-12 15:28  helloworldlee  阅读(370)  评论(0编辑  收藏  举报