掌握 Go 語言 Interface:面試高頻考點詳解

一、interface

1、interface 作用

2、eface 空接口

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

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. See mbitmap.go for details.
  gcdata    *byte
  str       nameOff
  ptrToThis typeOff  // type for pointer to this type, may be zero
}

3、iface 帶方法的接口

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

type itab struct {
  inter  *interfacetype      // 接口自身的元信息
  _type  *_type           // 具體類型的元信息
  link   *itab
  bad    int32
  hash   int32           // _type裏也有一個同樣的hash,此處多放一個是爲了方便運行接口斷言
  fun    [1]uintptr        // 函數指針,指向具體類型所實現的方法
}
// interface type包含了一些關於interface本身的信息,比如package path,包含的method
type interfacetype struct {
  typ     _type
  pkgpath name
  mhdr    []imethod
}
type imethod struct {      //這裏的 method 只是一種函數聲明的抽象,比如  func Print() error
  name nameOff
  ityp typeOff
}

4、interface 設計的優缺點

本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源https://mp.weixin.qq.com/s/7eOhqIJxHtnWbHQEencv4w