Defining method sets

June 9, 2023

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:

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 (where T is neither a pointer nor an interface) is the set of all methods declared with receiver *T or T.
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


Share this

Direct to your inbox, daily. I respect your privacy .

Unsure? Browse the archive .

Get daily content like this in your inbox!

Subscribe