【golang】结构体嵌套规则

64 阅读1分钟
  1. 方法接收者决定接口实现

    type I interface{ M() }
    type TA struct{}
    func (t *TA) M() {}  // 方法接收者是 *TA
    
    • *TA 实现了接口 I
    • TA 的值类型 没有 实现接口 I
  2. 结构体嵌入的继承规则

    type TB struct{ TA }  // 嵌入的是 TA(值类型)
    
    • TB 的方法集包含 TA 的方法集(但 TA 本身没有 M() 方法)
    • *TB 的方法集包含 *TA 的方法集(包含 M() 方法)

go文档——Struct_types,有这么一段关键信息:

image.png

Given a struct type S and a type name T, promoted methods are included in the method set of the struct as follows:

  • If S contains an embedded field T, the method sets of S and *S both include promoted methods with receiver T. The method set of *S also includes promoted methods with receiver *T.
  • If S contains an embedded field *T, the method sets of S and *S both include promoted methods with receiver T or *T.

明确说明了当S嵌套T时,*S类型的方法集除了包含T的方法集,还包含*T的方法集。