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

Direct to your inbox, daily. I respect your privacy .

Unsure? Browse the archive .

Related Content


Go 1.24.0 is here!

Go 1.24 is released! Yay! That means a short re-visit to the Go spec, as we look at things that have changed. From the release notes we see that there’s really only one significant change: Changes to the language¶ Go 1.24 now fully supports generic type aliases: a type alias may be parameterized like a defined type. See the language spec for details. For now, the feature can be disabled by setting GOEXPERIMENT=noaliastypeparams; but the aliastypeparams setting will be removed for Go 1.


Pointer Arithmetic

I mentioned a few days ago that pointer arithmetic is possible through the unsafe package. Here’s how to do it. Package unsafe … The function Add adds len to ptr and returns the updated pointer unsafe.Pointer(uintptr(ptr) + uintptr(len)) [Go 1.17]. The len argument must be of integer type or an untyped constant. A constant len argument must be representable by a value of type int; if it is an untyped constant it is given type int.


Package unsafe

Today we’re venturing into dangerous territory… the unsafe package! You can go years working in Go (as I have) without ever using unsafe, or just barely bumping into it. On the other hand, somd developers spend significant time using unsafe, to get the utmost performance out of their code, by working around the type system. Using unsafe can be powerful and beneficial. But… do it with the understanding that you’re giving up the benefits of memory and type safety, and cross-platform compatibility.

Get daily content like this in your inbox!

Subscribe