Generics
A type parameter lets one function work for many types, and the compiler checks each call. Here are the rules, the errors the compiler really prints, the code it really produces, and the measured cost.
- 1A constraint is a type set. The set decides which operators and methods the body may use.
- 2Use a type parameter when the code is the same for each type and a caller keeps the type. If a method is all you need, use an interface.
- 3Go compiles one body per GC shape and passes a dictionary. Value code stays fast; a method call on T costs about the same as an interface call.
- 4A generic method can take its own type parameters since Go 1.27, but it cannot implement an interface.
package main
import "fmt"
type Set[T comparable] map[T]struct{}
func (s Set[T]) Add(v T) { s[v] = struct{}{}2 }
func main() {
s := Set[any]{}1
s.Add(1)
s.Add("a")
fmt.Println("len:", len(s))
s.Add([]int{1})3
fmt.Println("len:", len(s))
}- 1any satisfies comparable since Go 1.20, because two interface values can be compared. The compiler says nothing.
- 2The map hashes the key. The hash looks at the dynamic type.
- 3A slice has no hash, so this call panics. The panic comes from a line with no type error.
| key type | recorded output | status |
|---|---|---|
| Set[any] | panic: runtime error: hash of unhashable type []int | Run-time panic |
| Set[string] | len: 2, len: 3 | Approved |
| Set[[]int] | []int does not satisfy comparable | Compile error |
- comparable means "== compiles", not "== is always safe".
- An interface type, or a struct that holds one, passes the check and can still panic.
- comparable has no strict form that refuses interface types. Choose a concrete type argument.
comparable accepts interface types since Go 1.20, so a Set of any can panic at run time. I use a concrete key type.
- Full stenciling makes one body per type. Boxing makes one body for all types. Go sits between them.
- Two types have the same GC shape if they have the same underlying type, or if both are pointers.
- Each call passes a dictionary as a hidden first argument. The compiler builds all dictionaries at compile time.
- The dictionary holds the type arguments, derived types such as []T, sub-dictionaries, and entries for method calls on T.
- In the recorded program, 16 type arguments gave 11 bodies and 16 dictionaries.
Go compiles one body per GC shape. Types with the same underlying type share a body, and all pointers share one. A dictionary carries the real types.
| constraint | type set | the body can use |
|---|---|---|
| any | Every type | Assignment, conversion to any, new, and a pointer to it. No operators. |
| comparable | Types that support ==, also interface types | == and != and a map key. Can panic with an interface argument. |
| cmp.Ordered | Integers, floats, strings, and named types over them | < <= > >= == !=, and + on all of them |
| int | string | Exactly int and string | Operators that all members share. MyInt is not a member. |
| ~int | ~string | Every type with underlying type int or string | The same operators. MyInt is a member. |
| interface{ String() string } | Types with that method | The method. A plain interface does this too. |
| interface{ ~int; String() string } | The intersection of both lines | Operators and the method. |
An interface with a union or a ~ term is a constraint only. It cannot be the type of a variable.
A constraint is an interface read as a set of types. The body can use only what every type in the set supports.
| you write | the compiler prints | do this |
|---|---|---|
| Pass MyInt to T int | string | MyInt does not satisfy int | string (possibly missing ~ for int in int | string) | Write ~int in the constraint. |
| a + b with T any | invalid operation: operator + not defined on a (variable of type T constrained by any) | Use cmp.Ordered or a union. |
| v.(type) with v of type T | cannot use type switch on type parameter value v (variable of type T constrained by any) | Write any(v).(type), and ask if an interface fits better. |
| New() where only the result uses T | in call to New, cannot infer T | Name it: New[int](). |
| A method needs more than the type declares | T does not satisfy cmp.Ordered | Write a function with the stronger constraint. |
| var x Number, where Number holds a union | cannot use type Number outside a type constraint: interface contains type constraints | Use it only in a type parameter list. |
| Decode[T any]() in an interface | interface method must have no type parameters | Make the interface generic, or use a function. |
| A generic method for an interface method | cannot use Name{} (value of struct type Name) as Stringer value in variable declaration: Name does not implement Stringer (wrong type for method String) | Add a method with no type parameters. |
I can name each refusal: a missing tilde, an operator that any lacks, a type switch on T, and an interface method with type parameters.
| situation | use | status |
|---|---|---|
| A container: a set, a stack, a cache | Type parameter | Approved |
| A slice or map algorithm with the same code for each type | Type parameter, or the slices and maps packages | Approved |
| The caller must get its own type back | Type parameter | Approved |
| The body only calls methods | Interface | T adds nothing |
| The behaviour differs per type | Interface | T hides a switch |
| One type exists today | Plain function | Wait for the second |
| The body needs reflection to work | reflect, or code generation | If no constraint fits |
| Decoding into a type the caller names | Type parameter | Approved |
// Writer needs no type parameter: it uses a method and
// nothing else, so an interface says the same thing.
type Writer interface {
Write(p []byte) (int, error)
}
// Greet is the plain version. Use this one.
func Greet(w Writer) error {
if _, err := w.Write([]byte("hello")); err != nil {
return fmt.Errorf("greet: %w", err)
}
return nil
}
// GreetT adds a type parameter and removes nothing.
func GreetT[W Writer](w W) error1 {
if _, err := w.Write([]byte("hello")); err != nil {
return fmt.Errorf("greet: %w", err)
}
return nil
}- 1The same body with a type parameter. It adds syntax and gives the caller nothing.
I add a type parameter when two copies of the code differ only in a type. If the body only calls a method, I take an interface.
// Number is a type set: int, int64, float64, and every
// type whose underlying type is one of those.
type Number interface {
~int | ~int64 | ~float641
}
// Sum keeps the named slice type S out of the result:
// only the element type E comes back.
func Sum[S ~[]E, E Number2](s S) E {
var total E3
for _, v := range s {
total += v
}
return total
}- 1The tilde admits named types, such as a Celsius over float64.
- 2Constraint type inference: the caller writes Sum(temps), and E follows from S.
- 3The zero value of E. This works for every type in the set.
S ~[]E takes a named slice type. Inference finds S from the argument, then finds E from the constraint on S.
// Map applies f to each element.
func Map[T, U any]1(in []T, f func(T) U) []U {
out := make([]U, 0, len(in))
for _, v := range in {
out = append(out, f(v))
}
return out
}
// Filter keeps the elements that pass the test.
func Filter[S ~[]T, T any](in S, keep func(T) bool2) S {
var out S
for _, v := range in {
if keep(v) {
out = append(out, v)
}
}
return out
}- 1Two parameters: U comes from the function argument. Map(ids, strconv.Itoa) needs no brackets.
- 2Taking S returns the same named type that came in.
A loop is often shorter. The slices package already has Sort, Index, Contains and many more.
Filter returns S, not []T, so a named slice type survives the call.
// Set is a defined type, so it can have methods.
type Set[T comparable] map[T]struct{}1
// Add puts v in the set. A map key is hashed here.
func (s Set[T]) Add2(v T) { s[v] = struct{}{} }
// Has reports whether v is in the set.
func (s Set[T]) Has(v T) bool {
_, ok := s[v]
return ok
}
// SortedItems is a function, not a method, because it
// needs a stronger constraint than Set declares.
func SortedItems[T cmp.Ordered]3(s Set[T]) []T {
return slices.Sorted(maps.Keys(s))
}- 1A defined type, so it can have methods. A map key needs comparable.
- 2The receiver repeats the parameter name, with no constraint.
- 3Set[T] accepts T here because cmp.Ordered types are comparable.
A method cannot tighten the constraint of its type, so Sorted is a function with cmp.Ordered.
// Cache is safe for concurrent use.
type Cache[K comparable, V any] struct {
mu sync.Mutex
m map[K]V
}
// NewCache makes the map, so the zero value of Cache
// is not used by accident.
func NewCache[K comparable, V any]() *Cache[K, V]1 {
return &Cache[K, V]{m: make(map[K]V)}
}
// Put stores v under k.
func (c *Cache[K, V]) Put(k K, v V) {
c.mu.Lock()
defer c.mu.Unlock()
c.m[k] = v
}
// Get returns the value, or the zero V and false.
func (c *Cache[K, V]) Get(k K) (V, bool)2 {
c.mu.Lock()
defer c.mu.Unlock()
v, ok := c.m[k]
return v, ok
}- 1A constructor names the type arguments once: NewCache[int, string]().
- 2The miss returns the zero V, so the bool is the only reliable test.
A generic store is one mutex and one map, with no conversions at the call site.
// Option holds a value or nothing.
type Option[T any] struct {
v T
ok bool
}
// Some wraps a value.
func Some[T any](v T) Option[T] { return Option[T]{v, true} }
// None is the empty Option.
func None[T any]() Option[T] { return Option[T]{} }
// Get returns the value and whether it exists.
func (o Option[T]) Get() (T, bool) { return o.v, o.ok }
// Map has its own type parameter U. Before Go 1.27 this
// had to be a function: Map(o, f), not o.Map(f).
func (o Option[T]) Map[U any](f func(T) U) Option[U]1 {
if !o.ok {
return None[U]()2
}
return Some(f(o.v))
}- 1T comes from the receiver and U from this method. Each call site picks U, by inference or by name.
- 2The method returns a different instantiation of its own type.
A generic method cannot implement an interface method. See the last two rows of panel D.
Since Go 1.27, a method can declare its own type parameters. So Map chains on the value, and it does not need a package function.
// Client reads JSON documents by key.
type Client struct {
Docs map[string]string
}
// Get decodes the document into any type the caller
// names. The type stays at the call site: c.Get[User].
func (c *Client) Get[T any](key string) (T, error)1 {
var v T
doc, ok := c.Docs[key]
if !ok {
return v, fmt.Errorf("get %q: no such key", key)
}
if err := json.Unmarshal([]byte(doc), &v)2; err != nil {
return v, fmt.Errorf("get %q: %w", key, err)
}
return v, nil
}- 1T appears only in the result, so the caller writes it: c.Get[User]("u1").
- 2A pointer to T: the decoder sees the real type through the interface value.
A decoding client is the natural generic method: the caller names the type, and the client keeps its state.
// Index is the same type as map[K][]V, not a new type.
type Index[K comparable, V any] = map[K][]V1
// Store is an old name for Cache. Old callers compile
// while they move to the new name.
type Store[K comparable, V any] = Cache[K, V]2- 1The equals sign makes an alias. A plain map value needs no conversion.
- 2The migration case: old code keeps the old name, and both names are one type.
A generic alias gives a type a second name, so I can move a generic type between packages and not break callers.
// Setter says: P is *T, and *T has a Set method.
type Setter[T any] interface {
*T
Set(string) error
}
// Parse needs both T, to allocate the slice, and P, to
// call a pointer method on each element.
func Parse[T any, P Setter[T]]2(in []string) ([]T, error) {
out := make([]T, len(in))
for i, s := range in {
if err := P(&out[i]).Set(s)3; err != nil {
return nil, fmt.Errorf("item %d: %w", i, err)
}
}
return out, nil
}- 1A type set with one member: *T. So P can only be a pointer to T.
- 2The caller writes Parse[level](in). P follows from the constraint.
- 3Convert, then call. A plain T cannot call a pointer method.
When T's methods have pointer receivers, I add a second parameter P that is constrained to *T, and call through it.
// Lesser refers to itself in its own parameter list.
// Go 1.26 lifted the rule that forbade this.
type Lesser[T Lesser[T]] interface1 {
Less(T) bool
}
// MinOf returns the smallest argument.
func MinOf[T Lesser[T]](first T, rest ...T) T {
low := first
for _, v := range rest {
if v.Less(low)2 {
low = v
}
}
return low
}- 1Go 1.25 refuses this line. The self-reference now compiles.
- 2A method call on T goes through the dictionary, so it does not inline.
Since Go 1.26 a generic type can refer to itself in its own parameter list, so a constraint can name the type it constrains.
// Person is sorted by two fields.
type Person struct {
Name string
Age int
}
// ByAgeThenName sorts in place. cmp.Or returns the first
// result that is not zero, so ties fall to the name.
func ByAgeThenName(p []Person) {
slices.SortFunc(p, func(a, b Person) int {
return cmp.Or(1
cmp.Compare(a.Age, b.Age)2,
cmp.Compare(a.Name, b.Name),
)
})
}- 1Go 1.22. It returns the first argument that is not the zero value.
- 2Go 1.21. It returns -1, 0 or 1, and it orders NaN before every number.
cmp.Compare gives a three-way result, and cmp.Or takes the first result that is not zero, so a multi-field sort is three lines.
Describe[go.shape.int]int, MyIntDescribe[go.shape.int64]int64Describe[go.shape.float64]float64, CelsiusDescribe[go.shape.string]stringDescribe[go.shape.struct { X int }]A, BDescribe[go.shape.struct { S string }]CDescribe[go.shape.*uint8]*A, *B, *stringDescribe[go.shape.[]int][]intDescribe[go.shape.[]main.MyInt][]MyIntDescribe[go.shape.interface {}]anyDescribe[go.shape.interface { Error() string }]error
Code: Describe[go.shape.int]
Dictionary: .dict.Describe[main.MyInt]
Shares this code with: int.
16 type arguments, 11 compiled functions, 16 dictionaries.
- The function is one line: it prints the type of its argument with %T. The compiler kept it out of line for this test.
- int and int64 have the same size on this machine, but each has its own body.
- any and error are both interfaces, but they have different bodies. An interface is never in a shape with a non-interface type.
int and MyInt share a body. []int and []MyInt do not, because their underlying types differ.
| work | concrete or generic | interface | what it shows |
|---|---|---|---|
| Add an element | concrete 0.29 ns; generic 0.29 ns | 1.56 ns | Once Sum inlines, a test finds the same opcodes as the concrete loop. Any gap here is noise. Interface elements need a dynamic call each. |
| Call a method in a loop | concrete 1.21 ns; T value 1.35 ns; T pointer 1.35 ns | 1.35 ns | A method on T uses the dictionary, so it is an indirect call like an interface call. |
| Push and pop 1,024 ints | 2.4 µs; 0 allocations | 12.3 µs; 1,024 allocations | A []any boxes each of these ints. A []T stores the int directly. |
| Sort 1,024 ints | slices.Sort 24.0 µs | sort.Sort 55.9 µs | The comparison stays in line, so the generic sort is 2.3 times faster here. |
Go 1.27.3, 8-core Intel i9 laptop, GOMAXPROCS 16, median of 5 interleaved runs of 1 s, on a busy machine. Compare sizes, not small differences.
Generic value code runs close to concrete code. A method call on T costs about the same as an interface call. The big gain is no boxing.
| since | what changed | what it means here |
|---|---|---|
| 1.18 | Type parameters, type sets, any, comparable, and inference. | The start of generics. |
| 1.20 | Interface types satisfy comparable, even though a comparison can panic. | Set[any] compiles. See panel A. |
| 1.21 | Packages slices, maps and cmp. Inference takes generic functions as arguments, considers methods, and handles mixed untyped constants. | Map(ids, strconv.Itoa) and Max(1, 2.5) work. |
| 1.22 | cmp.Or. math/rand/v2 with a generic rand.N. | Multi-field comparisons in one expression. |
| 1.24 | Generic type aliases are fully supported. Go 1.23 had a preview behind an experiment. | Move a generic type and keep the old name. |
| 1.25 | The specification drops core types. No program changes. | Old articles use a term that is gone. |
| 1.26 | A generic type can refer to itself in its type parameter list. errors.AsType is generic. | Panel N. See G7 for AsType. |
| 1.27 | Methods can declare type parameters. Interface methods cannot, and a generic method cannot implement one. Function inference applies to every assignment and conversion. math/rand/v2 Rand has a generic method N. | Panels J and K. The infer-assign drill question. |
| when | the moment | what to do or say |
|---|---|---|
| build | You start the store. | Write a concrete map of your one entity. A generic store costs typing time and buys nothing with one type. |
| build | You need Sort, Index or Contains. | Use the slices package. Do not write Map and Filter helpers. |
| build | Two handlers decode JSON in the same way. | One small function with a type parameter is fine: T appears at the call site. |
| talk | "Why not an interface here?" | An interface hides the type and boxes values. A type parameter keeps the type and stores values directly. |
| talk | "Why not generics here?" | The body calls one method, so an interface says the same with less syntax. |
| talk | "How does Go compile this?" | One body per GC shape, plus a dictionary per type argument. Name the cost from panel Q. |
| talk | "Does generic code cost more?" | Arithmetic stays close to concrete code. A method call on T is indirect. Boxing is the cost that generics remove. |
I write the concrete type first. I generalize when the second type arrives, and I say so.
0 of 9 known
Predict the output.
package main import "fmt" type MyInt int func Kind[T any](v T) string { switch any(v).(type) { case int: return "int" case string: return "string" } return "other" } func main() { fmt.Println(Kind(1)) fmt.Println(Kind("a")) fmt.Println(Kind(MyInt(1))) }Predict the output. The second call has T = any.
package main import "fmt" func IsZero[T comparable](v T) bool { var zero T return v == zero } func main() { var p *int var a any = p fmt.Println(IsZero(p)) fmt.Println(IsZero(a)) fmt.Println(IsZero[any](nil)) }Predict the output.
package main import ( "cmp" "fmt" ) func Max[T cmp.Ordered](a, b T) T { if a > b { return a } return b } func main() { x := Max(1, 2.5) fmt.Printf("%v %T\n", x, x) y := Max(1, 2) fmt.Printf("%v %T\n", y, y) }Predict the output.
package main import "fmt" type Alias[T comparable] = map[T]bool type Defined[T comparable] map[T]bool func main() { a := Alias[string]{"x": true} d := Defined[string]{"x": true} fmt.Printf("%T\n", a) fmt.Printf("%T\n", d) _, ok := any(a).(map[string]bool) fmt.Println(ok) _, ok = any(d).(map[string]bool) fmt.Println(ok) }Predict the output.
package main import "fmt" type MyInt int type Box[T any] struct{ V T } func Name[T any](v T) string { return fmt.Sprintf("%T", v) } func main() { fmt.Println(Name(1)) fmt.Println(Name(MyInt(1))) fmt.Println(Name(Box[MyInt]{1})) var a any = Box[int]{1} _, ok := a.(Box[MyInt]) fmt.Println(ok) }Predict the output.
package main import ( "cmp" "fmt" "math" "slices" ) func main() { nan := math.NaN() fmt.Println(nan < 1, cmp.Less(nan, 1)) fmt.Println(nan == nan, cmp.Compare(nan, nan)) fmt.Println(min(nan, 1), slices.Min([]float64{1, nan})) s := []float64{2, nan, 1} slices.Sort(s) fmt.Println(s) }Predict the output. This needs Go 1.27.
package main import ( "fmt" "strconv" ) type Box[T any] struct{ V T } func (b Box[T]) Map[U any](f func(T) U) Box[U] { return Box[U]{f(b.V)} } func main() { b := Box[int]{21} s := b.Map(func(n int) int { return n * 2 }).Map(strconv.Itoa) fmt.Printf("%T %q\n", s, s.V) f := Box[int].Map[string] fmt.Printf("%T\n", f) }Predict the output. This needs Go 1.27.
package main import "fmt" func Twice[T any](v T) []T { return []T{v, v} } type Job struct { Run func(string) []string } func main() { var f func(int) []int = Twice j := Job{Run: Twice} list := []func(bool) []bool{Twice} g := (func(float64) []float64)(Twice) fmt.Println(f(1), j.Run("a"), list[0](true), g(1.5)) }Predict the output.
package main import "fmt" func Zero[T any]() T { var v T return v } func First[T any](s []T) T { if len(s) == 0 { return *new(T) } return s[0] } func main() { fmt.Printf("%q\n", Zero[string]()) fmt.Println(Zero[*int]() == nil) fmt.Println(Zero[[2]int]()) fmt.Println(First[int](nil)) fmt.Println(Zero[error]() == nil) }
- shapes
- 16 type arguments gave 11 bodies and 16 dictionaries.
- sum
- 0.29 ns concrete and 0.29 ns generic, per element.
- method on T
- 1.35 ns per call, against 1.35 ns for an interface.
- boxing
- []any is 5.2 times slower than []T, with 1,024 allocations against 0.
- sort
- slices.Sort is 2.3 times faster than sort.Sort.
Go 1.27.3, 8-core Intel i9 laptop, on a busy machine. Use these as orders of magnitude.