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

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?

Receiver uniqueness

Today I’ll be love coding again. I hope you can join me! I’ll be continuing where I left off, working on the backlog for my open-source CouchDB SDK, https://kivik.io/. Join me to see how many mistakes a senior Go dev makes while coding. Method declarations … A non-blank receiver identifier must be unique in the method signature. If the receiver’s value is not referenced inside the body of the method, its identifier may be omitted in the declaration.