Search code examples
gomethodsstructembedding

Golang type embedding implement


I have a type T which embed type B, and *B implements I. *T can be assigned to a variable of type I but not in the case of T, does this mean (*T)'s method set contains both value and pointer receiver of 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()
}


Solution

  • Yes, method set of *T contains methods with receiver B and *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.