Method within selectors

September 1, 2023

Method declarations

The method is said to be bound to its receiver base type and the method name is visible only within selectors for type T or *T.

This short sentence is a bit tricky to parse, because it relies on some as-yet unfamilar concepts. But it’s really pretty straight forward once those concepts are understood.

A selector expression looks something like foo.bar. So given the following type and method:

type foo int

func (f foo) bar() {}

the method bar is bound to the receiver base type foo, and the method name is only visible within selectors for foo or *foo. All other references to bar do not refer to this method.

So to further expand the example to illustrate:

var x foo

x.bar() // A valid selector expression. x is of type `foo`, so `bar` refernces the method on `foo`

var y *foo

y.bar() // Also valid, y is of type `*foo`

var z int

z.bar() // Invalid. z is of type int, which has no method `bar` bound to it.

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

Share this

Related Content

Type parameters in method definitions

Yesterday we saw that when a method is defined on a generic type, the receiver must include type parameters. Now for all the relevant details: Method declarations … … Syntactically, this type parameter declaration looks like an instantiation of the receiver base type: the type arguments must be identifiers denoting the type parameters being declared, one for each type parameter of the receiver base type. The type parameter names do not need to match their corresponding parameter names in the receiver base type definition, and all non-blank parameter names must be unique in the receiver parameter section and the method signature.

Methods on generic types

Ready to dive back into generics, this time with regard to methods? Great, ‘cause here we go! Method declarations … If the receiver base type is a generic type, the receiver specification must declare corresponding type parameters for the method to use. Okay. Before we continue, let’s make sure we all know exactly what we’re talking about. What does it mean for a receiver base type to be a generic type?

Uniqueness of methods

Oops! Yesterday I live-streamed… to the wrong link! If you followed the link I shared yesterday, you were probably confused. But the good news is, you can still catch the replay. Method declarations … For a base type, the non-blank names of methods bound to it must be unique. If the base type is a struct type, the non-blank method and field names must be distinct. These uniqueness rules are quite predictible!