Methods aren't for "objects"

July 24, 2023

I’ll be livestreaming again today, in just a few minutes. Join me live, or watch the replay. I’ll be picking up where I left off, with my new linter project.

One of the most powerful things I like about Go, is the ability to put methods on any type.

Type definitions

Type definitions may be used to define different boolean, numeric, or string types and associate methods with them:

type TimeZone int

const (
	EST TimeZone = -(5 + iota)

func (tz TimeZone) String() string {
	return fmt.Sprintf("GMT%+dh", tz)

In many other languages, if you want to associated a method with, say, an integer, you have to wrap that integer in an Object. Not so in Go. With Go, you can just define a custom type, with an underlying type of int, and put methods on it!

You can even put methods on funcion types, which seems a bit strange at first, but is also very powerful. There’s actually a good chance you’ve already used this pattern, perhaps without realizign it, if you use the net/http pacakge. The type HandlerFunc is such an example:

type HandlerFunc func(ResponseWriter, *Request)

This type, which is a function type, has a single method defined on it:

func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request)

Quotes from The Go Programming Language Specification Version of December 15, 2022

Share this

Related Content

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.

Methods on generic types

Ready to dive back into generics, this time with regard to methods? Great, ‘cause here we go! Method declarations … If the receiver base type is a generic type, the receiver specification must declare corresponding type parameters for the method to use. Okay. Before we continue, let’s make sure we all know exactly what we’re talking about. What does it mean for a receiver base type to be a generic type?

Uniqueness of methods

Oops! Yesterday I live-streamed… to the wrong link! If you followed the link I shared yesterday, you were probably confused. But the good news is, you can still catch the replay. Method declarations … For a base type, the non-blank names of methods bound to it must be unique. If the base type is a struct type, the non-blank method and field names must be distinct. These uniqueness rules are quite predictible!