Method receiver base types

August 25, 2023

There’s a lot to unpack about method receiver types, so we’ll do it over two days.

Method declarations

The receiver is specified via an extra parameter section preceding the method name. That parameter section must declare a single non-variadic parameter, the receiver.

This bit is fairly straight forward. The receiver is specified in an extra parameter section preceeding the method name:

func (reciever ReceiverType) MethodName(/* 0 or more regular arguments */) { /* ... */}

Futher, only a single argument is allowed, and it may not be variadic. In other words, there can be only a single receiver for a method.

func (receiver1 ReceiverType, receiver2 Othertype) Method() {} // Invalid

func (receivers ...ReceiverType) Method() {} // Invalid

Its type must be a defined type T or a pointer to a defined type T, possibly followed by a list of type parameter names [P1, P2, …] enclosed in square brackets.

So we can define methods on generic types… we’ll see how that works in detail soon.

T is called the receiver base type.

There we have it. The type of the receiver argument is the base type of the method.

func (r Receiver) Method1() // Method1's base type is Receiver

func (r *Receiver) Method2() // Method2's base type is *Receiver

Quotes from The Go Programming Language Specification Version of August 2, 2023

Share this