Receiver uniqueness

September 4, 2023

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. The same applies in general to parameters of functions and methods.

No surprises here. We already know that function parameters and named return values must be unique within the function signature. The same is true for the receiver.

func (f Foo) Frobnicate(f filename) error { // Invalid, `f` is not unique
	/* ... */
}

Further, the receiver name can be either blank, or omitted (preferred), if it’s not referenced within the body of the method. This same rule applies to function parameters that are not referenced.

func (_ Dog) Speak() string { // Blank receiver, since it's not used
	return "woof"
}

func (Cat) Speak() string { // Receiver name omitted entirely, since it's not used
	return "meow"
}

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


Method values

A quick reminder: In today’s live stream, I’ll be deploying a Go app to Kubernetes! I hope you’ll join me! Today we continue the explanation of Method values. There’s nothing too surprising today. The spec mostly just confirms what should seem natural… Method values … As in the discussion of method expressions above, consider a struct type T with two methods, Mv, whose receiver is of type T, and Mp, whose receiver is of type *T.


Method expressions, part 2

Today I’ll continue where I left off yesterday, talking about… Method expressions … Similarly, the expression (*T).Mp yields a function value representing Mp with signature func(tp *T, f float32) float32 The key difference to notice between this example and yesterday’s is that the first argument (that of the receiver) is a pointer here, but was not a pointer in the previous example: func(tv T, a int) int // First argument of type T, not a pointer func(tp *T, f float32) float32 // First argument of type *T, a pointer For a method with a value receiver, one can derive a function with an explicit pointer receiver, so


Method expressions

There was no livestream today, as I was a bit under the weather. I intend to be back live streaming next Monday as usual Method expressions If M is in the method set of type T, T.M is a function that is callable as a regular function with the same arguments as M prefixed by an additional argument that is the receiver of the method. MethodExpr = ReceiverType "." MethodName .

Get daily content like this in your inbox!

Subscribe