Golang 类型嵌入工具

Golang type embedding implement

我有一个嵌入了类型B的类型T,*B实现了I。*T可以赋值给类型I的变量,但是T不能赋值,这是否意味着(*T)的方法set 包含 B 的值和指针接收器?

package main

import (
    "fmt"
)

type I interface {
    Foo()
}
type B struct {}
type T struct {
    B
}

func (a *B) Foo() {
    fmt.Println("Bar")
}

func main() {
    t := T{B{}}
    // var i I = t -> error
    var i I = &t
    i.Foo()
}

是,*T 的方法集包含接收者为 B*B 的方法。

Spec: Struct types:

Given a struct type S and a defined type 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.