Generic type aliases and generic methods
suggest changeThe Generics article covers what shipped in Go 1.18: generic functions, generic types, constraints. Since then generics have gained several features that remove the most common "you can't do that" moments:
| Feature | Go version |
|---|---|
| Better type inference: generic functions as arguments and in assignments, inference from interface methods, mixed untyped constants | 1.21 |
Generic type aliases: type Set[T comparable] = map[T]struct{} |
1.24 |
Constraints that refer to themselves: type Adder[A Adder[A]] interface{...} |
1.26 |
Generic methods: func (l List[E]) Map[F any](...) |
1.27 |
| Generic functions inferred in all assignment contexts (struct literals, map values, channel sends) | 1.27 |
Language features are tied to the go line in go.mod, so you need go 1.27 (or later) there to use everything shown below.
Better type inference (Go 1.21)
Go 1.21 taught the compiler to infer type arguments in places where Go 1.18 required you to spell them out:
package main
import (
"cmp"
"fmt"
"slices"
)
type Getter[T any] interface {
Get() T
}
// GetAll calls Get on each value.
func GetAll[T any](gs ...Getter[T]) []T {
var r []T
for _, g := range gs {
r = append(r, g.Get())
}
return r
}
type Port int
func (p Port) Get() int { return int(p) }
func Larger[T cmp.Ordered](a, b T) T {
if a > b {
return a
}
return b
}
func descending[T cmp.Ordered]() func(a, b T) int {
return func(a, b T) int { return cmp.Compare(b, a) }
}
func main() {
words := []string{"pear", "fig", "banana", "apple"}
// 1. A generic function passed to a generic function:
// E = string comes from words, so cmp.Compare is cmp.Compare[string].
slices.SortFunc(words, cmp.Compare)
fmt.Println(words)
// 2. Assigned to a variable of a known function type.
var cmpInts func(a, b int) int = cmp.Compare
fmt.Println(cmpInts(3, 1))
// 3. Inferred from the methods of an interface: T = int.
fmt.Println(GetAll(Port(80), Port(443)))
// 4. Untyped constants of different kinds: T = float64.
fmt.Println(Larger(1, 2.5))
// Inference never looks at how a result is used, so this needs [int].
nums := []int{3, 1, 2}
slices.SortFunc(nums, descending[int]())
fmt.Println(nums)
}
[apple banana fig pear]
1
[80 443]
2.5
[3 2 1]
The same four cases (written without cmp and slices, which didn't exist yet) fail with Go 1.20 (line numbers are from that version of the program):
main.go:37:24: default type float64 of 2.5 does not match inferred type int for T
main.go:38:26: cannot use generic function Compare without instantiation
main.go:39:29: cannot use generic function Compare without instantiation
main.go:41:9: type Port of Port(80) does not match Getter[T] (cannot infer T)
What inference still can't do: work backwards from the result. descending() has no arguments that mention T, and the compiler doesn't look at the fact that the result goes to SortFunc with a []int:
i2\main.go:57:34: in call to descending, cannot infer T (declared at i2\main.go:33:17)
cmp.Compare, cmp.Less, cmp.Or and the cmp.Ordered constraint are covered in Equality and comparison and Sorting.
Generic type aliases (Go 1.24)
A type alias gives another name to an existing type. Since Go 1.24 an alias can have type parameters:
package main
import (
"fmt"
"maps"
"slices"
)
// A generic alias: Set[T] is just another name for map[T]struct{}.
type Set[T comparable] = map[T]struct{}
func Add[T comparable](s Set[T], vals ...T) {
for _, v := range vals {
s[v] = struct{}{}
}
}
func main() {
s := Set[string]{}
Add(s, "go", "rust", "go")
// s is a plain map, so all map operations and the maps package work on it.
var m map[string]struct{} = s
fmt.Println(len(m), slices.Sorted(maps.Keys(s)))
fmt.Printf("%T\n", s)
}
2 [go rust]
map[string]struct {}
Set[string] and map[string]struct{} are the same type; %T doesn't even know the alias exists. Compare this with a type definition, type Set[T comparable] map[T]struct{}, which creates a new type that can have methods.
That's the trade-off. An alias can't have methods, and it can't alias its own type parameter. Generic aliases must also be instantiated when used:
package main
type Set[T comparable] = map[T]struct{}
// Not allowed: methods on a generic alias.
func (s Set[T]) Has(v T) bool {
_, ok := s[v]
return ok
}
// Not allowed: the aliased type can't be the type parameter itself.
type Same[T any] = T
func main() {
var s Set // must be instantiated
_ = s
}
e1\main.go:6:9: cannot define new methods on generic alias type Set[T comparable]
e1\main.go:12:20: cannot use type parameter declared in alias declaration as RHS
e1\main.go:15:8: cannot use generic type Set[T comparable] without instantiation
Moving a generic type to another package
Aliases exist mainly for refactoring: you move a type to a new package and leave an alias behind so old code keeps compiling. Before Go 1.24 this didn't work for generic types; type Cache = lru.Cache is an error because lru.Cache must be instantiated. Now you can forward the type parameters:
// lru/lru.go
package lru
// Cache is the new home of the type.
type Cache[K comparable, V any] struct {
items map[K]V
}
func New[K comparable, V any]() *Cache[K, V] {
return &Cache[K, V]{items: map[K]V{}}
}
func (c *Cache[K, V]) Put(k K, v V) { c.items[k] = v }
func (c *Cache[K, V]) Get(k K) (V, bool) {
v, ok := c.items[k]
return v, ok
}
// cache/cache.go
// Package cache is the old location, kept for compatibility.
package cache
import "gen7/a2/lru"
// Deprecated: use lru.Cache.
type Cache[K comparable, V any] = lru.Cache[K, V]
// Deprecated: use lru.New.
func New[K comparable, V any]() *Cache[K, V] { return lru.New[K, V]() }
// An alias can also fix some of the type arguments.
type ByName[V any] = lru.Cache[string, V]
package main
import (
"fmt"
"gen7/a2/cache"
"gen7/a2/lru"
)
func useNew(c *lru.Cache[string, int]) {
v, _ := c.Get("a")
fmt.Println("a =", v)
}
func main() {
old := cache.New[string, int]()
old.Put("a", 1)
useNew(old) // same type, no conversion
var byName *cache.ByName[int] = old
byName.Put("b", 2)
v, ok := old.Get("b")
fmt.Println("b =", v, ok)
fmt.Printf("%T\n", byName)
}
a = 1
b = 2 true
*lru.Cache[string,int]
Because cache.Cache[string, int] is identical to lru.Cache[string, int], packages can migrate one at a time. All the methods of lru.Cache are available through the alias.
ByName[V] shows the other use: an alias with fewer type parameters that fixes some of them. That's handy for long instantiations that appear all over a codebase, but don't overdo it. Every alias is one more name a reader has to look up.
Constraints that refer to themselves (Go 1.26)
Sometimes a method needs to take or return "the same type as the receiver": Add(A) A, Less(T) bool, Clone() T. The constraint for that is F-bounded: the type parameter appears in its own constraint. In Go 1.26 an interface can express that about itself:
package main
import "fmt"
// Adder is satisfied by any type A that has a method Add(A) A.
// The constraint refers to itself: A must be an Adder[A].
type Adder[A Adder[A]] interface {
Add(A) A
}
func Sum[A Adder[A]](xs ...A) A {
var total A
for _, x := range xs {
total = total.Add(x)
}
return total
}
type Vec struct{ X, Y int }
func (v Vec) Add(o Vec) Vec { return Vec{v.X + o.X, v.Y + o.Y} }
type Money int64 // cents
func (m Money) Add(o Money) Money { return m + o }
func (m Money) String() string { return fmt.Sprintf("$%d.%02d", m/100, m%100) }
func main() {
fmt.Println(Sum(Vec{1, 2}, Vec{3, 4}, Vec{10, 20}))
fmt.Println(Sum[Money](199, 250, 1))
}
{14 26}
$4.50
Go 1.25 rejects the declaration of Adder:
.\main.go:7:6: invalid recursive type: Adder refers to itself
.\main.go:14:17: total.Add undefined (type A has no field or method Add)
Functions could always say [A Adder[A]]. Before 1.26 you declared type Adder[A any] interface{ Add(A) A } and repeated the A Adder[A] bound in every function. Now the interface states the rule once and the compiler checks it everywhere the interface is instantiated:
package main
type Adder[A Adder[A]] interface {
Add(A) A
}
type Vec struct{ X, Y int }
func (v Vec) Add(o Vec) Vec { return Vec{v.X + o.X, v.Y + o.Y} }
func main() {
var a Adder[Vec] = Vec{1, 2} // ok
var b Adder[int] // int has no Add method
_, _ = a, b
}
e4\main.go:13:14: int does not satisfy Adder[int] (missing method Add)
A more practical example: a tree where every node returns children of its own type. Walk gets concrete *Dir values, so the callback doesn't need type assertions:
package main
import (
"fmt"
"strings"
)
// Node is a tree node whose children are the same kind of node.
type Node[N Node[N]] interface {
Children() []N
}
// Walk visits n and all its descendants depth-first.
// It returns concrete N values, not an interface, so no type assertions.
func Walk[N Node[N]](n N, visit func(n N, depth int)) {
var walk func(N, int)
walk = func(n N, depth int) {
visit(n, depth)
for _, c := range n.Children() {
walk(c, depth+1)
}
}
walk(n, 0)
}
type Dir struct {
Name string
Subs []*Dir
}
func (d *Dir) Children() []*Dir { return d.Subs }
func main() {
root := &Dir{Name: "/", Subs: []*Dir{
{Name: "etc"},
{Name: "usr", Subs: []*Dir{{Name: "bin"}, {Name: "lib"}}},
}}
Walk(root, func(d *Dir, depth int) {
fmt.Println(strings.Repeat(" ", depth) + d.Name)
})
}
/
etc
usr
bin
lib
Generic methods (Go 1.27)
Until Go 1.27 a method could use only the type parameters of its receiver. A method couldn't add type parameters of its own, so anything that changed the element type had to be a top-level function. Now it can:
package main
import (
"fmt"
"math/rand/v2"
"strconv"
"strings"
"time"
)
type List[E any] []E
// Map has its own type parameter F, in addition to the receiver's E.
func (l List[E]) Map[F any](f func(E) F) List[F] {
r := make(List[F], len(l))
for i, x := range l {
r[i] = f(x)
}
return r
}
func (l List[E]) Filter(keep func(E) bool) List[E] {
var r List[E]
for _, x := range l {
if keep(x) {
r = append(r, x)
}
}
return r
}
func main() {
nums := List[int]{1, 2, 3, 4, 5, 6}
// F is inferred from the argument: string.
strs := nums.Filter(func(n int) bool { return n%2 == 0 }).
Map(strconv.Itoa).
Map(func(s string) string { return "#" + s })
fmt.Println(strings.Join(strs, " "))
// Explicit instantiation works like for functions.
halves := nums.Map[float64](func(n int) float64 { return float64(n) / 2 })
fmt.Println(halves)
// math/rand/v2 got a generic method in Go 1.27.
r := rand.New(rand.NewPCG(1, 2))
d := r.N(10 * time.Second) // T inferred as time.Duration
fmt.Printf("%T %v\n", d, d < 10*time.Second)
fmt.Printf("%T\n", r.N[uint8](200))
}
#2 #4 #6
[0.5 1 1.5 2 2.5 3]
time.Duration true
uint8
With a top-level Map function (see Map, filter, and reduce) the chain above reads inside out: Map(Map(Filter(nums, ...), strconv.Itoa), ...). With methods it reads left to right.
The standard library uses the feature in math/rand/v2. Before 1.27 rand.N[T] was a top-level function using the global source only. (*rand.Rand).N now does the same for your own seeded generator.
A non-generic type can have generic methods too. This is useful for "get a value of type T" APIs:
package main
import (
"encoding/json"
"fmt"
)
// Store keeps raw JSON values by key.
type Store struct {
data map[string]json.RawMessage
}
func NewStore(js string) (*Store, error) {
s := &Store{}
err := json.Unmarshal([]byte(js), &s.data)
return s, err
}
// Get decodes the value under key into a T.
func (s *Store) Get[T any](key string) (T, error) {
var v T
raw, ok := s.data[key]
if !ok {
return v, fmt.Errorf("key %q not found", key)
}
err := json.Unmarshal(raw, &v)
return v, err
}
// GetOr returns def if the key is missing or has the wrong type.
// T is inferred from def.
func (s *Store) GetOr[T any](key string, def T) T {
v, err := s.Get[T](key)
if err != nil {
return def
}
return v
}
type Limits struct {
MaxConns int `json:"max_conns"`
}
// App embeds *Store; generic methods are promoted like any other method.
type App struct {
*Store
Name string
}
func main() {
s, err := NewStore(`{"port": 8080, "hosts": ["a", "b"], "limits": {"max_conns": 100}}`)
if err != nil {
panic(err)
}
port, err := s.Get[int]("port")
fmt.Println(port, err)
hosts, _ := s.Get[[]string]("hosts")
fmt.Println(hosts, len(hosts))
limits, _ := s.Get[Limits]("limits")
fmt.Printf("%+v\n", limits)
_, err = s.Get[string]("port")
fmt.Println(err)
fmt.Println(s.GetOr("timeout", 30), s.GetOr("port", 80))
app := App{Store: s, Name: "demo"}
fmt.Println(app.GetOr("hosts", []string{}))
}
8080 <nil>
[a b] 2
{MaxConns:100}
json: cannot unmarshal number into Go value of type string
30 8080
[a b]
Get has no argument of type T, so the caller has to write s.Get[int](...). GetOr takes def T, so T is inferred from it.
Method values and method expressions
Like a generic function, a generic method has to be instantiated before you can use it as a value. You can do that explicitly, or let the compiler infer it from the type of the variable:
package main
import (
"fmt"
"reflect"
"strconv"
)
type Box struct{ v int }
func (b Box) Get[T any](conv func(int) T) T { return conv(b.v) }
func (b Box) String() string { return "Box(" + strconv.Itoa(b.v) + ")" }
func main() {
b := Box{42}
// A method value must be instantiated, explicitly...
getStr := b.Get[string]
fmt.Println(getStr(strconv.Itoa))
// ...or by inference from the type it's assigned to.
var getF func(func(int) float64) float64 = b.Get
fmt.Println(getF(func(n int) float64 { return float64(n) / 10 }))
// Method expressions work too.
get := Box.Get[bool]
fmt.Println(get(b, func(n int) bool { return n > 0 }))
// Generic methods are not part of the method set seen by reflection.
t := reflect.TypeOf(b)
for i := range t.NumMethod() {
fmt.Println("method:", t.Method(i).Name)
}
}
42
4.2
true
method: String
Without an instantiation or a target type, f := b.Get fails:
e3\main.go:9:7: cannot use generic function b.Get without instantiation
The reflection output shows something important. A generic method isn't one method; it's a family of methods, one per type argument, created at compile time. There's nothing for reflect to list or call.
Generic methods and interfaces
That's also why generic methods don't mix with interfaces. An interface can't declare a method with type parameters, and a generic method doesn't satisfy an interface method, even one that matches an instantiation of it:
package main
import "fmt"
// Not allowed: interface methods can't have type parameters.
type Mapper interface {
Map[F any](func(int) F) []F
}
type Box struct{ v int }
func (b Box) Get[T any](conv func(int) T) T { return conv(b.v) }
// An interface whose method looks like one instantiation of Get.
type StringGetter interface {
Get(func(int) string) string
}
func main() {
var g StringGetter = Box{42}
fmt.Println(g)
}
e2\main.go:7:5: interface method must have no type parameters
e2\main.go:7:23: undefined: F
e2\main.go:20:23: cannot use Box{…} (value of struct type Box) as StringGetter value in variable declaration: Box does not implement StringGetter (wrong type for method Get)
have Get[T any](func(int) T) T
want Get(func(int) string) string
A call through an interface is resolved at run time, but generic code is instantiated at compile time. When a Box is stored in an interface, the compiler doesn't know which Get[T] will be needed later, so it can't generate it. If you need a value to satisfy an interface, give it a regular method (GetString) next to the generic one.
Generic methods also need go 1.27 in go.mod. With an older language version you get:
.\main.go:7:18: generic method requires go1.27 or later (-lang was set to go1.26; check go.mod)
When to use a generic method
- Use one when the operation belongs to the type and a chain of calls reads better than nested function calls:
list.Map(...).Filter(...),store.Get[T](key),rng.N(d). - Use a top-level generic function when it isn't tied to one receiver type, e.g.
slices.Indexworks on any slice. - If the method must be part of an interface (mocking, plugins,
io.Writer-style abstractions), it can't be generic.
Inference in all assignment contexts (Go 1.27)
Go 1.21 inferred type arguments when a generic function was passed as an argument or assigned to a variable. Go 1.27 extends this to every place where a value is assigned to something of known function type: struct fields in composite literals, slice and map elements, and channel sends:
package main
import "fmt"
type Number interface {
~int | ~int64 | ~float64
}
func Double[T Number](v T) T { return v * 2 }
func Square[T Number](v T) T { return v * v }
type Step struct {
Name string
F func(int) int
}
func main() {
// Struct fields in a composite literal.
steps := []Step{{"double", Double}, {"square", Square}}
for _, s := range steps {
fmt.Println(s.Name, s.F(7))
}
// Map values.
ops := map[string]func(float64) float64{"double": Double, "square": Square}
fmt.Println(ops["square"](1.5))
// Channel sends.
ch := make(chan func(int64) int64, 1)
ch <- Double
fmt.Println((<-ch)(21))
}
double 14
square 49
2.25
42
Go 1.25 wanted Double[int], Square[float64] and so on:
.\main.go:19:29: cannot use generic function Double without instantiation
.\main.go:19:49: cannot use generic function Square without instantiation
.\main.go:25:52: cannot use generic function Double without instantiation
.\main.go:25:70: cannot use generic function Square without instantiation
.\main.go:30:8: cannot use generic function Double without instantiation
Note: the Go 1.27.0 compiler crashes with internal compiler error: ... is not assignable to ... when a generic function from another package is used this way, e.g. []func(a, b string) int{cmp.Compare} or ch <- slices.Index. The type checker accepts the code (go vet passes) but the build fails. Until that's fixed, instantiate imported functions explicitly: cmp.Compare[string]. Generic functions from your own package, as above, work fine.
Summary
- Go 1.21: generic functions can be passed to other generic functions (
slices.SortFunc(s, cmp.Compare)) and assigned to typed variables; type arguments are inferred from interface methods and from mixed untyped constants. - Go 1.24:
type Set[T comparable] = map[T]struct{}declares a generic alias. It's the same type as what it aliases and can't have methods. Use it to move generic types between packages or to fix some type arguments. - Go 1.26: an interface can constrain its own type parameter (
type Adder[A Adder[A]] interface{ Add(A) A }). - Go 1.27: methods can declare their own type parameters (
func (l List[E]) Map[F any](...)). They can't appear in interfaces, don't satisfy interface methods and are invisible toreflect. - Go 1.27: generic functions are inferred in struct literals, slice and map literals and channel sends; in 1.27.0, instantiate imported generic functions explicitly there to avoid a compiler crash.