Uniqueness of methods

September 5, 2023

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! But let’s go over it to be complete, anyway.

type X int

func (X) Foo() {}

func (x *X) Foo() {} // Invalid; Foo is already defined as a method on this type

Or in the case of a struct:

type Person struct {
	Name string
}

func (p *Person) Name() string { // Invalid. Name cannot be a field and a method
	return p.Name
}

The spec continues with an example, which we’ll get out of the way today so that tomorrow we can talk about generics as they relate to methods.

Given defined type Point the declarations

func (p *Point) Length() float64 {
	return math.Sqrt(p.x * p.x + p.y * p.y)
}

func (p *Point) Scale(factor float64) {
	p.x *= factor
	p.y *= factor
}

bind the methods Length and Scale, with receiver type *Point, to the base type Point.

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 .

Related Content


Go 1.24.0 is here!

Go 1.24 is released! Yay! That means a short re-visit to the Go spec, as we look at things that have changed. From the release notes we see that there’s really only one significant change: Changes to the language¶ Go 1.24 now fully supports generic type aliases: a type alias may be parameterized like a defined type. See the language spec for details. For now, the feature can be disabled by setting GOEXPERIMENT=noaliastypeparams; but the aliastypeparams setting will be removed for Go 1.


Refresher on methods

In yesterday’s email, I failed to include the example included in the spec, which doesn’t make sense to include otherwise. I’ve updated the web version of the email in case you’re super curious to see what I left out. We’ve already covered these details, but they’re logically mentioned again in the section about function calls, so we’ll cover them here: Calls … A method call x.m() is valid if the method set of (the type of) x contains m and the argument list can be assigned to the parameter list of m.


Method values, part 2

Today we finish up the spec’s section on method values, with some very non-surprising bits: Method values … As with selectors, a reference to a non-interface method with a value receiver using a pointer will automatically dereference that pointer: pt.Mv is equivalent to (*pt).Mv. As with method calls, a reference to a non-interface method with a pointer receiver using an addressable value will automatically take the address of that value: t.

Get daily content like this in your inbox!

Subscribe