Skip to main content

Method Set

A method set is a Golang feature. The compiler knows the set of methods for a type. This set is based on the method receiver type.

A method receiver can be a value or a pointer. The compiler decides the method set from the variable type.

Regular methods vs interface methods

For regular methods, a T or T type can call a method with a T orT receiver. No restriction applies.

The restriction of T variable not being able to call methods of *T receiver applies only to interfaces.

Worry about method sets only when working with interfaces.

From Golang FAQ

This distinction arises because if an interface value contains a pointer *T, a method call can obtain a value by de-referencing the pointer, but if an interface value contains a value T, there is no safe way for a method call to obtain a pointer. Doing so would allow a method to modify the contents of the value inside the interface, which isn't permitted by the language specification.

Selector

A selector is the . operator. You use it to call a method or access a field.

When you use the dot operator on a type, the compiler knows its methods from the method set.

Method Sets of interface

  1. Value receivers work on a copy of the value. You can call them with a T or *T. If T is known, the compiler gets the address with & to call the method.
  2. Pointer receivers can be called only with pointer types. Only an interface of type *T can call them.
Method vs Function

In all languages, know the difference between a function and a method. All methods are functions. But not all functions are methods.

A method is a function tied to a type, struct, or class.

Sources

Understanding Method Sets in Go (semanticreatures.com)
A detailed explanation of how method sets work in Go, including practical examples and diagrams.

Pointer vs Value Methods in Go (gronskiy.com)
A comparison of pointer and value receivers in Go, with code samples and best practices.