1

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()
}

1 Answer 1

8

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.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.