A method in Go is a function attached to a type. A generic method is a method that declares its own type parameters, allowing it to work with types that are not fixed by its receiver.
Consider a generic list:
E represents the type of the elements stored in the list. Say:
Now suppose we want a method that transforms every element:
This method uses two type parameters:
– E belongs to the receiver, List[E].
– R belongs to the method itself and represents the result type.
That distinction is important. A List[int] already determines that E is int, but each call to Map may produce a different type:
Here, the compiler infers that R is string from the transformation function. Conceptually, the method converts:
A regular method on a generic type can use only the type parameters declared by its receiver:
A generic method goes further by introducing additional type parameters of its own:
This makes generic methods particularly useful for operations such as mapping, converting, decoding, or wrapping values—any operation whose output type may differ from the receiver’s existing type.
Generic methods follow the same central idea as generic functions: write the behavior once while preserving compile-time type safety. The difference is simply that the behavior belongs to a type and can be called using ordinary method syntax.
This syntax is specified in Go 1.27’s section on method declarations(https://go.dev/ref/spec#Method_declarations.