Limitations on methods
August 28, 2023
Today I’ll be love coding again. I hope you can join me! I’ll be working on the backlog for my open-source CouchDB SDK, https://kivik.io/ to add a long-missing feature. Join me to see how many mistakes a senior Go dev makes while coding.
Method declarations
…
A receiver base type cannot be a pointer or interface type and it must be defined in the same package as the method.
This tiny sentence has three distinct cases to consider. We’ll take one per day, and discuss potential work-arounds to each limitation.
A receiver base type cannot be a pointer.
This means the following is invalid:
type foo *string
func (f foo) DoSomething() {} // invalid receiver type foo (pointer of interface type)
If you really want a method on a pointer type, you can wrap it in a struct, for example:
type foo struct {
str *string
}
func (f foo) DoSomething() {} // Now you can access f.str to do what you wish.
Quotes from The Go Programming Language Specification Version of August 2, 2023