Generics
Generics let you write a function or type once, with type parameters, and use it with many concrete types. Constraints say which operations those types must support.
Detailed Explanation
Before Go 1.18, min for integers meant several functions, or interface{} and type assertions. Generics give you func Min[T cmp.Ordered](a, b T) T. The compiler produces type-checked instantiations. You keep static types; you do not lose them in any.
Type parameters sit in brackets. func Keys[K comparable, V any](m map[K]V) []K has two parameters. Callers usually omit them: Keys(users) infers K and V from the map. Write Keys[string, User](users) when inference cannot see the types.
Constraints replace "what can I do with T." any means no methods, no operators except those that work on every type (assign, pass). comparable means == is allowed, which is what map keys need. cmp.Ordered (in cmp) means < works. You can write your own interface constraint with methods, or a type set of listed types.
Generic types. type Set[T comparable] map[T]struct{} is a named type with a parameter. Methods on Set can use T. There are no generic methods on non-generic types: you cannot write func (s Store) Get[T any](id string) T. Put the parameter on the type, or keep Get as a function.
When not to genericize. A function that only works on []byte should take []byte. A pair of types that share behaviour should often be an interface the caller already implements. Generics shine for containers (Set, Result), slice helpers (slices.Index, maps.Keys), and numeric helpers. They add noise when there is only one instantiation you will ever write.
What it costs. Compile time grows with instantiations, not with a VM-style erasure tax at runtime. The generated code is close to what you would have written by hand. The human cost is constraints that are too tight (int only when int64 should work) or too loose (any plus a panic). Prefer a constraint in the standard library (cmp.Ordered, constraints.Integer) before you invent one.
Code Examples
package main
import (
"cmp"
"fmt"
)
func Min[T cmp.Ordered](a, b T) T {
if a < b {
return a
}
return b
}
func main() {
fmt.Println(Min(3, 5), Min("a", "b"))
}type Set[T comparable] map[T]struct{}
func (s Set[T]) Add(v T) { s[v] = struct{}{} }
func (s Set[T]) Has(v T) bool {
_, ok := s[v]
return ok
}func Keys[K comparable, V any](m map[K]V) []K {
out := make([]K, 0, len(m))
for k := range m {
out = append(out, k)
}
return out
}Common Gotchas
No generic methods on ordinary types
the type parameter must be on the type or the function. Interfaces cannot have type parameters on methods either.
Inference fails on empty or nil untyped arguments
`Min(nil, nil)` does not compile. Pass typed values or explicit type arguments.
`any` as a constraint forbids `<` and `==`
add `comparable` or a type set when you need operators.
Instantiation is per type set used
`Min[int]` and `Min[string]` are different functions at compile time.