Generic Methods

Learn how methods behave on generic types in Go 1.27, including methods that declare their own type parameters.

Go added support for generics in version 1.18, introducing type parameters for functions and types. When people talk about "generic methods" in Go, they usually mean one of two things: methods defined on a generic type, or methods that introduce their own type parameters independent of the receiver. Before Go 1.27 only the first form existed. Go 1.27 supports both: a method declaration may now declare its own type parameters, in addition to any the receiver type already has.

A method on a named slice type can now map each element to a new type of the caller's choosing:

type Slice[T any] []T
func (s Slice[T]) Map[V any](fn func(T) V) []V {
    result := make([]V, len(s))
    for i, v := range s {
        result[i] = fn(v)
    }
    return result
}

Calling Slice[int]{1, 2, 3}.Map(func(v int) int { return v * 10 }) returns [10 20 30]. The method brings its own type parameter V, while T comes from the receiver. The same works on a non-generic receiver: a Cache type with no type parameters of its own can declare func (c *Cache) Get[T any](key string) (T, bool), and callers write c.Get[int]("k") or let the compiler infer T from the assignment.

One restriction survives: interface methods still may not declare type parameters. A generic method cannot implement an interface method, because an interface method set cannot express a method that is generic over a fresh type parameter.

This section assumes Go 1.27.

Methods on Generic Types

How to define methods on generic types in Go 1.27: repeating the receiver's type parameters, renaming them, using the blank identifier for parameters a method does not need, and declaring fresh type parameters on the method itself. It also covers the errors you will hit when the receiver list is wrong, and when a standalone generic function is still the better choice.

Summary

Methods on generic types reuse the type parameters declared on the type itself, and since Go 1.27 a method may also declare its own type parameters, on generic and non-generic receivers alike. The only place type parameters are still forbidden is in interface methods. When you need a function that works with multiple independent type parameters and does not belong to a particular type, a generic top-level function remains a good alternative.

Methods on Generic Types

Learn how to define methods on generic types in Go 1.27, including receiver type parameters and methods that declare their own type parameters.