eface 和 iface 区别?

532 阅读1分钟

eface 和 iface 区别?

eface

eface 表示空接口。其数据结构由类型信息_type 和数据信息data组成。


type eface struct {
   _type *_type // **type负责决定data应该如何解释和操作**
   data  unsafe.Pointer
}

_type数据结构:

type _type struct {
  size       uintptr 
  ptrdata    uintptr    // size of memory prefix holding all pointers
  hash       uint32     // 类型哈希
  tflag      tflag
  align      uint8      // _type作为整体变量存放时的对齐字节数
  fieldalign uint8
  kind       uint8
  alg        *typeAlg
  // gcdata stores the GC type data for the garbage collector.
  // If the KindGCProg bit is set in kind, gcdata is a GC program.
  // Otherwise it is a ptrmask bitmap
  gcdata    *byte
  str       nameOff
  ptrToThis typeOff  // type for pointer to this type, may be zero

图片.png

iface

iface 表示非空接口。非空接口初始化的过程就是初始化一个iface类型的结构,其中data的作用同eface的相同,

type iface struct {
  tab  *itab
  data unsafe.Pointer
}

itab 数据结构:


type itab struct {
  inter  *interfacetype   // 接口自身的元信息
  _type  *_type           // 具体类型的元信息
  link   *itab
  bad    int32
  hash   int32            // _type里也有一个同样的hash,此处多放一个是为了方便运行接口断言
  fun    [1]uintptr       // 函数指针,指向具体类型所实现的方法
}
​
type interfacetype struct {
  typ     _type
  pkgpath name
  mhdr    []imethod
}
​
type imethod struct {   //这里的 method 只是一种函数声明的抽象,比如  func Print() error
  name nameOff
  ityp typeOff
}

图片.png

1、_type 和与eface的 *type类型相同。

参考: zhuanlan.zhihu.com/p/76354559 research.swtch.com/interfaces