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

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

Unsure? Browse the archive .

Get daily content like this in your inbox!

Subscribe