Recall that every type in Go has a method set. Let’s examine how that’s defined:
Method sets
… Every type has a (possibly empty) method set associated with it:
- The method set of a defined type
T
consists of all methods declared with receiver typeT
.
type S struct { /* Possibly some fields */ }
// Foo() is a member of the method set of `S`, because it has a receiver type `S`.
func (s S) Foo() {}
type I int
// Foo() is also a member of the method set of `I`, because it has a reciver type `I`.
func (i I) Foo() {}
- The method set of a pointer to a defined type
T
(whereT
is neither a pointer nor an interface) is the set of all methods declared with receiver*T
orT
.
type F float64
// Foo() is a member of the method set of `*F` and `F`
func (f F) Foo() {}
// Bar() is a member of the method set of `*F`, but not `F`
func (f *F) Bar() {}
- The method set of an interface type is the intersection of the method sets of each type in the interface’s type set (the resulting method set is usually just the set of declared methods in the interface).
Further rules apply to structs (and pointer to structs) containing embedded fields, as described in the section on struct types. Any other type has an empty method set.
We’ve already discussed interface type sets, and embedded structs, so I won’t go into detail on that again.
In a method set, each method must have a unique non-blank method name.
Quotes from The Go Programming Language Specification Version of December 15, 2022