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