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

Share this

Related Content

Zero values of slices and maps

Composite literals … Note that the zero value for a slice or map type is not the same as an initialized but empty value of the same type. Let’s look at examples so we can understand exactly what is being stated here. Recall that when you declare a variable of a given type, the default value is the zero value for the type: var s1 []string // Zero value for slice var m1 map[string]int // Zero value for map What the spec is telling us is that the zero value of a slice or map is not the same as an initialized, but empty, slice or map:

Taking the address of literals

Composite literals … Taking the address of a composite literal generates a pointer to a unique variable initialized with the literal’s value. var pointer *Point3D = &Point3D{y: 1000} This particular feature of the language is immensely useful. Without it, the above code snippet would become much longer: var point Point3D = Point3D{y: 1000} var pointer *Point3D = &point In fact, this is the exact situation we are in for non-composites.

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.