Generics: Type Parameters, Constraints, Where They Help
"write Go programs by writing code, not by defining types." — Ian Lance Taylor, When To Use Generics, The Go Blog, 12 April 2022
Summary: Go generics let one function or type work for a set of types: type parameters in square brackets, constraints that are interfaces read as type sets, inference that usually spares you the type arguments, and a compiler that shares one body per GC shape. Focus: Type parameters and arguments, generic functions and types, constraints (any, comparable, cmp.Ordered, unions and ~T), methods in constraints, inference and explicit instantiation, the zero value of T, generic containers (Stack, Set, LRU), the generic standard library (slices, maps, cmp, iter, sync.OnceValue, atomic.Pointer, errors.AsType), iterators, aliases, Go 1.27 generic methods, GC shape stenciling with dictionaries, limitations, error messages, tooling, and when not to use generics. Learning goal: Read and write generic Go fluently, predict which calls compile and which errors you get, choose between a type parameter, an interface and reflection, and know what a type parameter costs at run time.
This page owns type parameters as the language and the gc toolchain implement them, read against the Go 1.27 specification (language version go1.27, May 26, 2026) with Go 1.27.4 installed. Interfaces as runtime values, type assertions and type switches are in Interfaces, Type Assertions, Type Switches & any; function values and closures are in Functions; the slice and map mechanics that slices and maps build on are in Arrays, Slices & Maps; reflect is in reflect: When and How; the full sync and atomic catalogue is in sync & atomic; benchmarking technique is in Testing & Benchmarking. The generic helpers that wrap a MongoDB collection are in MongoDB with Go.
Page map
| If you are looking for | Go to |
|---|---|
| The whole topic in three tables | Everything in one minute |
| Why Go waited until 1.18 and what problem generics solve | Why it exists |
| Proposal, release history 1.18 to 1.27 | Where it comes from |
func Map[T, U any], type parameter versus type argument | Type parameters and generic functions |
type Stack[T any] struct, methods on generic types | Generic types |
any, constraints as interfaces | Constraints |
Unions, ~int, underlying types, type sets | Type sets and ~T |
comparable, strictly comparable, runtime panic | comparable |
cmp.Ordered, golang.org/x/exp/constraints | cmp.Ordered and the constraints package |
A constraint with a method, the *T pattern | Methods in constraints |
Inference, cannot infer T, Map[string](...) | Type inference and explicit instantiation |
var zero T, *new(T) | The zero value of T |
| Stack, Set, LRU, Option and Result | Generic data structures |
slices, maps, cmp, sync.OnceValue, atomic.Pointer | The generic standard library |
iter.Seq, iter.Pull | Iterators with generics |
[S ~[]E, E any] | Deconstructing type parameters |
type Set[T comparable] = set.Set[T] | Generic type aliases |
func (l List[E]) Map[F any] | Generic methods (Go 1.27) and generic interfaces |
| How gc compiles generics, performance | GC shape stenciling and dictionaries |
| What still does not exist | Limitations |
| Over-abstraction, the official guidance | When to use generics |
go vet, gopls | Tooling |
PHPStan @template | For PHP/Laravel developers |
| Every compiler message verbatim | Exact messages |
| Fixes with code | Solving the classic problems |
| Type parameter, interface or reflection | Choosing |
| From one process to many services | In architecture |
| Reproduce the outputs | Lab |
| Wrong beliefs, cheat sheet, terms | Misconceptions, Cheat sheet, Glossary |
Everything in one minute
The vocabulary. Each row is unpacked in the concept catalogue.
| Term | Plain words | Tiny example |
|---|---|---|
| Type parameter | A placeholder for a type, declared in square brackets | T in func Max[T cmp.Ordered](a, b T) T |
| Type argument | The real type that replaces the placeholder | int in Max[int](1, 2) |
| Constraint | An interface that says which type arguments are allowed | cmp.Ordered, comparable, any |
| Type set | The set of types an interface permits | ~int, ~string union permits int, string, Celsius |
~T | "Any type whose underlying type is T" | ~int admits type Celsius int |
| Instantiation | Substituting type arguments and checking constraints | Max[int] is an ordinary func(int, int) int |
| Type inference | The compiler works out the type arguments | Max(1, 2) infers T = int |
| Generic type | A type with type parameters | Stack[T any], used as Stack[string] |
| GC shape | Group of types that share one compiled body | All pointer types share go.shape.*uint8 |
| Dictionary | Hidden argument carrying type information to a shared body | ..dict.Id[*int] |
What a constraint allows inside the body.
| Constraint | Operations allowed on values of type T | Example type arguments |
|---|---|---|
any | Assign, pass, store, compare with nothing, convert to any | Everything |
comparable | Everything of any plus == and !=, map keys | int, string, structs of comparable fields, pointers, any (since Go 1.20) |
cmp.Ordered | Plus <, <=, >, >=, and + for numbers and strings | Integers, floats, strings and named types over them |
Numeric union with ~ | Arithmetic common to every member, conversions | ~int, ~int64, ~float64 |
fmt.Stringer | Calls to String() | Any type with that method |
| Union plus method | Both the operators of the union and the method | interface { ~int64; String() string } |
When to reach for what.
| You need | Use | Not |
|---|---|---|
| The same code for many element types | Type parameter | Copy-paste or interface{} plus assertions |
| To call methods whose implementation differs per type | Interface type | [T io.Reader] |
| Behaviour that differs per type, types without methods | Reflection | Type parameter with a type switch |
| A container (stack, set, cache, tree) | Generic type | container/list with any |
| A lazy sequence | iter.Seq[T] | A goroutine plus channel |
| Lock-free typed pointer swap | atomic.Pointer[T] | atomic.Value plus assertion |
Why it exists
Before Go 1.18 you had two ways to write code that works for several types: write it again for each type, or write it once over interface{} and convert at run time. The first is safe and fast but repeats itself; the second is short but loses static type checking, boxes values, and pushes mistakes into panics. Type parameters add a third way: write once, keep compile-time checking, store values unboxed.
| Without type parameters | With type parameters |
|---|---|
SumInts, SumFloats, SumInt64s | One Sum[T Number] |
[]interface{} container, v.(int) on every read | Stack[int], reads return int |
Mistakes found at run time (panic: interface conversion) | Mistakes found at compile time (string does not satisfy Number) |
| Values boxed into interfaces (allocation for non-pointer values) | Values stored directly in the slice or node |
| Simpler type system, simpler tools | More concepts: constraints, inference, instantiation |
The everyday picture used through this page: a shipping box factory. The factory has one design for a box (the generic type), a slot on the order form for "what goes in it" (the type parameter), and a rulebook that says which goods are allowed (the constraint). Each order fills in the slot (the type argument), the clerk often fills it in from the goods you hand over (inference), and the factory does not build a new production line for every product: all goods of the same size and handling share one line (the GC shape), with a label telling the workers what is inside (the dictionary).
Three common misunderstandings, up front
- "Generics make code faster than interfaces." Not by default. gc shares one body per GC shape and passes a dictionary, so a method call through a type parameter is often as indirect as an interface call. The Go team's own words: using a type parameter "will generally not be faster than using an interface type." See GC shape stenciling.
- "A constraint is a new kind of thing." It is an ordinary interface, read as the set of types it permits. Interfaces that contain unions or
~Tterms may only be used as constraints. See Constraints. - "Go has no generic methods." True until Go 1.26. Go 1.27 adds methods with their own type parameters, but interface methods still cannot have them and generic methods cannot implement interface methods. See Generic methods.
Where it comes from
Go 1.0 shipped without generics. The FAQ explains the choice: "Generics are convenient but they come at a cost in complexity in the type system and run-time." Several designs (contracts, among others) were tried and dropped. The accepted design is Ian Lance Taylor and Robert Griesemer's Type Parameters Proposal (go.dev/design/43651-type-parameters), which made constraints plain interfaces and introduced type sets.
| Version | What changed for generics | Source |
|---|---|---|
| Go 1.18 | Type parameters, any, comparable, type sets, unions, ~T; golang.org/x/exp/constraints, x/exp/slices, x/exp/maps; vet updated for generic code | Go 1.18 release notes |
| Go 1.20 | comparable satisfied by all comparable types, including interfaces (may panic) | "All your comparable types" blog |
| Go 1.21 | slices, maps, cmp in the standard library; min/max built-ins; sync.OnceFunc, OnceValue, OnceValues; stronger inference (generic function arguments, assignment context, methods) | Go 1.21 release notes |
| Go 1.22 | math/rand/v2 with generic N; range over int | Go 1.22 release notes |
| Go 1.23 | iter package, range-over-func, iterator functions in slices and maps; preview of generic type aliases behind GOEXPERIMENT=aliastypeparams | Go 1.23 release notes |
| Go 1.24 | Generic type aliases fully supported | Go 1.24 release notes, "What's in an (Alias) Name?" |
| Go 1.25 | No language change; the spec drops the notion of core types in favour of dedicated prose | Go 1.25 release notes |
| Go 1.26 | A generic type may refer to itself in its own type parameter list (type Adder[A Adder[A]]); errors.AsType | Go 1.26 release notes |
| Go 1.27 | Generic methods; function type inference applies whenever a generic function is assigned or converted to a matching function type | Go 1.27 release notes |
Two documents you will read about generics are partly out of date, and saying so saves confusion. Effective Go states that "it does not cover significant changes to the language (generics)". The FAQ entry "Why does Go not support methods with type parameters?" still says "We do not anticipate that Go will ever add generic methods." The Go 1.27 release notes supersede it with a narrower feature: methods may declare type parameters, but "methods of interfaces may not declare type parameters nor can interface methods be implemented by generic methods", which is exactly the implementation problem the FAQ describes.
The concept catalogue
Every block follows the same order: plain words, the usual wrong belief, a precise definition, a timeline, real scenarios, a comparison table, and the fix in Go. The snippets live under docs/snippets/go/generics/go/ (one module, go 1.24 in go.mod, fourteen packages) and pass go vet and go test -race.
Type parameters and generic functions Must-know
In plain words: a generic function has an extra list of parameters in square brackets. Those parameters are types, not values. Each call fills them in with real types.
Common misunderstanding: "T is like any: the function receives values of any type at run time." No. Every call has exactly one type argument for T, fixed at compile time. Map([]int{1}, strconv.Itoa) is a call to Map[int, string]; you cannot pass a []string to that instantiation.
Definition: a type parameter list [P1 C1, P2, P3 C2] declares type parameters, each with a constraint. The spec: "A type parameter list declares the type parameters of a generic function, method, or type declaration." Inside the function a type parameter is a type like any other, but only the operations permitted by every type in its constraint's type set are allowed. A type argument is the concrete type supplied at instantiation. The function body is type-checked once, against the constraints, not once per type argument.
1 declare: func Map[T, U any](xs []T, f func(T) U) []U
2 call: Map([]int{1, 2}, strconv.Itoa)
3 infer: T = int (from []int), U = string (from func(int) string)
4 instantiate: Map[int, string] : func([]int, func(int) string) []string
5 check: int satisfies any, string satisfies any -> OK
6 compile: one body for the shape (go.shape.int, go.shape.string)Real scenario: a Map/Filter/Reduce toolkit used by every handler that converts database rows into API DTOs; a Keys helper that works for map[string]User and map[int64]Order; a Retry[T any](ctx, fn func() (T, error)) (T, error) that returns the typed result of the retried call; a MaxOf used for prices, timestamps and version strings.
| Aspect | Generic function Map[T, U any] | Function over any | Copy per type |
|---|---|---|---|
| Compile-time type check | Yes | No (assertions) | Yes |
| Values boxed | No | Yes for non-pointer values | No |
| Code size | One body per GC shape | One body | One body per type |
| Readability | Square brackets to learn | Assertions everywhere | Duplication |
Fix / how to use it: keep type parameter lists short and named by role (T, K, V, E, S); put type parameters that cannot be inferred first so callers can supply a prefix; prefer a function argument (cmp func(T, T) int) to a method constraint.
// Package basics shows generic functions, inference, explicit
// instantiation and the zero value of a type parameter.
package basics
import "cmp"
// Map returns f applied to each element. Two type parameters: the
// input element type T and the output element type U.
func Map[T, U any](xs []T, f func(T) U) []U {
out := make([]U, 0, len(xs))
for _, x := range xs {
out = append(out, f(x))
}
return out
}
// Filter keeps the elements for which keep returns true.
func Filter[T any](xs []T, keep func(T) bool) []T {
var out []T
for _, x := range xs {
if keep(x) {
out = append(out, x)
}
}
return out
}
// Reduce folds xs into an accumulator of type A.
func Reduce[T, A any](xs []T, init A, f func(A, T) A) A {
acc := init
for _, x := range xs {
acc = f(acc, x)
}
return acc
}
// MaxOf returns the largest element and false for an empty slice.
// cmp.Ordered permits <, <=, >, >= on the type parameter.
func MaxOf[T cmp.Ordered](xs []T) (T, bool) {
var zero T
if len(xs) == 0 {
return zero, false
}
m := xs[0]
for _, x := range xs[1:] {
if x > m {
m = x
}
}
return m, true
}
// Zero returns the zero value of T. T cannot be inferred from arguments,
// so callers must instantiate it explicitly: Zero[int]().
func Zero[T any]() T {
var zero T
return zero
}
// ZeroNew is the expression form of the same thing.
func ZeroNew[T any]() T { return *new(T) }
// Ptr returns a pointer to a copy of v, handy for optional fields.
func Ptr[T any](v T) *T { return &v }
// Keys returns the keys of any map. K must be comparable to be a map key.
func Keys[M ~map[K]V, K comparable, V any](m M) []K {
out := make([]K, 0, len(m))
for k := range m {
out = append(out, k)
}
return out
}package basics
import (
"slices"
"strconv"
"testing"
)
func TestInferenceFromArguments(t *testing.T) {
// T = int and U = string are inferred from the arguments.
got := Map([]int{1, 2, 3}, strconv.Itoa)
if !slices.Equal(got, []string{"1", "2", "3"}) {
t.Fatalf("Map: %v", got)
}
even := Filter([]int{1, 2, 3, 4}, func(n int) bool { return n%2 == 0 })
if !slices.Equal(even, []int{2, 4}) {
t.Fatalf("Filter: %v", even)
}
total := Reduce([]string{"a", "bb", "ccc"}, 0, func(acc int, s string) int { return acc + len(s) })
if total != 6 {
t.Fatalf("Reduce: %d", total)
}
}
func TestExplicitInstantiation(t *testing.T) {
// Partial instantiation: T given, U inferred from the function argument.
lens := Map[string]([]string{"go", "php"}, func(s string) int { return len(s) })
if !slices.Equal(lens, []int{2, 3}) {
t.Fatalf("lens: %v", lens)
}
// Instantiating without calling yields an ordinary function value.
maxInts := MaxOf[int]
if m, ok := maxInts([]int{3, 9, 2}); !ok || m != 9 {
t.Fatalf("maxInts: %d %v", m, ok)
}
if _, ok := MaxOf([]string{}); ok {
t.Fatal("empty slice must report ok=false")
}
}
func TestZeroValueOfT(t *testing.T) {
if Zero[int]() != 0 || Zero[string]() != "" || Zero[*int]() != nil {
t.Fatal("var zero T must be the zero value")
}
if ZeroNew[float64]() != 0 {
t.Fatal("*new(T) must be the zero value")
}
type opts struct{ Limit *int }
o := opts{Limit: Ptr(50)}
if *o.Limit != 50 {
t.Fatal("Ptr")
}
}
type Headers map[string]string
func TestKeysKeepsNamedMapTypes(t *testing.T) {
h := Headers{"b": "2", "a": "1"}
k := Keys(h) // M = Headers, K = string, V = string
slices.Sort(k)
if !slices.Equal(k, []string{"a", "b"}) {
t.Fatalf("Keys: %v", k)
}
}Generic types Must-know
In plain words: a type can have type parameters too. Stack[T] is a recipe; Stack[int] and Stack[string] are two real, different types made from it.
Common misunderstanding: "Stack is a type I can use on its own." It is not. A generic type must be instantiated wherever it is used: var s Stack fails with cannot use generic type Stack[T any] without instantiation. And Stack[int] and Stack[int64] are unrelated types: no conversion, no shared interface by default.
Definition: type Name[P C] TypeLiteral declares a generic defined type. Methods are declared with a receiver that names the type parameters again: func (s *Stack[T]) Push(v T). The receiver's names need not match the declaration's (func (p Pair[First, _]) First() First is legal), and the receiver constraints are implied by the type definition. A generic type may refer to itself inside its definition (next *node[T]); since Go 1.26 it may also refer to itself in its own type parameter list. A type parameter cannot be the whole right-hand side: type T[P any] P is rejected with cannot use a type parameter as RHS in type declaration.
1 type Stack[T any] struct{ items []T } // generic type: a recipe
2 var a Stack[int] // instantiated: items is []int
3 var b Stack[string] // a different type
4 a = b // compile error: mismatched types
5 a.Push(1); v, ok := a.Pop() // v is int; ok reports emptiness
6 var c Stack // cannot use generic type Stack[T any] without instantiationReal scenario: a typed work queue per job kind; a Page[T] response wrapper with Items []T and NextCursor string; a Tree[T] for an in-memory price index; a Pair[K, V] returned by a "top N" query.
| Declaration | Meaning | Note |
|---|---|---|
type Stack[T any] struct{ items []T } | Generic struct | Zero value usable if fields allow |
type Set[T comparable] map[T]struct{} | Generic map type | Methods on a map type are fine |
type List[E any] []E | Generic slice type | Indexing, range, append work |
type Pred[T any] func(T) bool | Generic function type | Can have methods |
func (s *Stack[T]) Push(v T) | Method of a generic type | Receiver re-declares T |
type Number interface{ ~int; ~float64 } | Wrong: a constraint lists terms with a vertical bar | See Type sets |
Fix / how to use it: make the zero value useful (var s Stack[int] works without a constructor); return (T, bool) from operations that can fail on an empty container; clear popped slots (s.items[n] = zero) so pointer elements can be collected.
// Package stack is a generic LIFO with an iterator and the Go convention
// of (value, ok) instead of an Option type.
package stack
import "iter"
// Stack is a LIFO of T. The zero value is an empty stack ready to use.
type Stack[T any] struct {
items []T
}
// Push adds values on top, last argument on top.
func (s *Stack[T]) Push(vs ...T) { s.items = append(s.items, vs...) }
// Pop removes and returns the top value. ok is false when empty.
func (s *Stack[T]) Pop() (T, bool) {
var zero T
if len(s.items) == 0 {
return zero, false
}
top := s.items[len(s.items)-1]
s.items[len(s.items)-1] = zero // drop the reference so the GC can free it
s.items = s.items[:len(s.items)-1]
return top, true
}
// Peek returns the top value without removing it.
func (s *Stack[T]) Peek() (T, bool) {
if len(s.items) == 0 {
var zero T
return zero, false
}
return s.items[len(s.items)-1], true
}
// Len reports the number of values.
func (s *Stack[T]) Len() int { return len(s.items) }
// All yields values from top to bottom without removing them.
func (s *Stack[T]) All() iter.Seq[T] {
return func(yield func(T) bool) {
for i := len(s.items) - 1; i >= 0; i-- {
if !yield(s.items[i]) {
return
}
}
}
}package stack
import (
"slices"
"testing"
)
func TestStack(t *testing.T) {
var s Stack[int]
if _, ok := s.Pop(); ok {
t.Fatal("zero Stack must be empty")
}
s.Push(1, 2, 3)
if v, _ := s.Peek(); v != 3 {
t.Fatalf("Peek = %d", v)
}
if got := slices.Collect(s.All()); !slices.Equal(got, []int{3, 2, 1}) {
t.Fatalf("All = %v", got)
}
v, ok := s.Pop()
if !ok || v != 3 || s.Len() != 2 {
t.Fatalf("Pop = %d %v len %d", v, ok, s.Len())
}
}
func TestStackOfPointersClearsSlot(t *testing.T) {
var s Stack[*[1 << 10]byte]
s.Push(new([1 << 10]byte))
s.Pop()
if s.items[:1][0] != nil {
t.Fatal("popped slot must be cleared")
}
}
func TestEarlyBreak(t *testing.T) {
var s Stack[string]
s.Push("a", "b", "c")
var seen []string
for v := range s.All() {
seen = append(seen, v)
if v == "b" {
break // yield returns false; All must stop
}
}
if !slices.Equal(seen, []string{"c", "b"}) {
t.Fatalf("seen %v", seen)
}
}Constraints Must-know
In plain words: a constraint is the rulebook that says which types may be plugged in. In Go the rulebook is always an interface.
Common misunderstanding: "Constraints are optional, like C++ templates." Every type parameter has a constraint; any is the loosest. And "an interface with a union is a normal interface type I can declare variables of": var n Number fails with cannot use type Number outside a type constraint: interface contains type constraints.
Definition: a type constraint is an interface. "A type T satisfies a constraint C if T implements C," or, as an exception since Go 1.20, T is a comparable (not necessarily strictly comparable) type and C is or embeds comparable. any is an alias for interface{} and permits every type. A constraint can be written inline: [T interface{ ~int; String() string }], and an interface with a single type term can be abbreviated in a type parameter list: [T ~int] means [T interface{ ~int }]. Interfaces that contain type terms (unions, ~T, non-interface types) or embed comparable are "general interfaces" and may only appear as constraints.
1 type Number interface{ ~int | ~float64 } // general interface: constraint only
2 func Sum[T Number](xs []T) T // OK
3 Sum([]int{1, 2}) // int is in the type set -> OK
4 Sum([]string{"a"}) // string does not satisfy Number (string missing in ~int | ~float64)
5 var n Number // cannot use type Number outside a type constraintReal scenario: Sum[T Number] over money amounts held as Cents int64; Index[T comparable] over IDs; a Validate[T Validator] helper where Validator is a method-only interface; a metrics histogram that accepts any integer or float type.
| Constraint form | Usable as an ordinary interface type? | Example |
|---|---|---|
| Method-only interface | Yes | fmt.Stringer, io.Reader |
any | Yes | []any |
comparable | No | [K comparable] |
| Interface with a union | No | Number from the snippet (~int or ~int64 joined by a vertical bar) |
Interface with ~T | No | interface{ ~string } |
| Union plus methods | No | interface{ ~int64; String() string } |
| Inline single term | Only in type parameter lists | [T ~int] |
Fix / how to use it: name reusable constraints (Number, Integer), keep them in the package that needs them, and use cmp.Ordered rather than re-declaring an ordered union.
// Package after replaces both habits with one type-parameterised version.
package after
// Number is a constraint: the type set of every type whose underlying type
// is one of these numeric types.
type Number interface {
~int | ~int8 | ~int16 | ~int32 | ~int64 |
~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 |
~float32 | ~float64
}
// Sum adds values of any Number type, including named types such as Cents.
func Sum[T Number](xs []T) T {
var s T // zero value of T
for _, x := range xs {
s += x
}
return s
}
// Stack is a LIFO of T; the compiler rejects a value of any other type.
type Stack[T any] struct {
items []T
}
// Push adds v on top.
func (s *Stack[T]) Push(v T) { s.items = append(s.items, v) }
// Pop removes and returns the top value; ok is false when the stack is empty.
func (s *Stack[T]) Pop() (v T, ok bool) {
if len(s.items) == 0 {
return v, false
}
v = s.items[len(s.items)-1]
s.items = s.items[:len(s.items)-1]
return v, true
}package after
import "testing"
type Cents int64
func TestSumAcceptsNamedTypes(t *testing.T) {
if got := Sum([]int{1, 2, 3}); got != 6 {
t.Fatalf("int: %d", got)
}
if got := Sum([]float64{1.5, 2.5}); got != 4 {
t.Fatalf("float64: %v", got)
}
// ~int64 in Number admits Cents; the result type is Cents, not int64.
var total Cents = Sum([]Cents{199, 1})
if total != 200 {
t.Fatalf("Cents: %d", total)
}
}
func TestStackIsTypeSafe(t *testing.T) {
var s Stack[string]
s.Push("a")
s.Push("b")
// s.Push(3) would not compile: cannot use 3 (untyped int constant) as string value
if v, ok := s.Pop(); !ok || v != "b" {
t.Fatalf("got %q %v", v, ok)
}
s.Pop()
if v, ok := s.Pop(); ok || v != "" {
t.Fatalf("empty pop: %q %v", v, ok)
}
}Type sets, unions and ~T underlying types Must-know
In plain words: read every interface as a list of the types it allows. A union int | string allows exactly those two types. Adding ~ widens a term to "every type built on top of it", so ~int also allows type Celsius int.
Common misunderstanding: "int | float64 accepts my type Cents int." It does not: MyInt does not satisfy Number (possibly missing ~ for int in Number). The compiler even suggests the fix. The opposite mistake is ~MyInt, which is illegal because the underlying type of MyInt is int, not MyInt.
Definition: the spec defines the type set of each interface element. A method-only interface's type set is every type with those methods. A term T denotes the single type T; a term ~T denotes all types whose underlying type is T, and in ~T the type T must be its own underlying type (a predeclared type or a type literal) and not an interface. A union t1 | t2 is the union of the term sets; the lines of an interface are intersected. The underlying type of type Celsius int is int; of type Emails []string it is []string; of time.Duration it is int64. Operations allowed on a value of type parameter type are those that every type in the type set supports. A union with more than one term may not contain an interface with methods, and embedding a type parameter in an interface is not allowed. The Go blog puts it plainly: "Interfaces as type sets is a powerful new mechanism and is key to making type constraints work in Go."
constraint type set (examples) Celsius (int)? time.Duration?
1 int | string {int, string} no no
2 ~int | ~string {int, Celsius, string, UserID, ...} yes no (int64)
3 ~int64 {int64, time.Duration, Cents, ...} no yes
4 interface{ ~int64; String() string } {Cents if it has String(), Duration} no yes
5 ~MyInt illegal: underlying type of MyInt is not MyIntReal scenario: a Clamp[T Integer] used for Celsius and Percent named types; a ParseID[T ~string] that returns UserID or OrderID with no conversion at the call site; an Abs[T Signed] in a geometry library; a Bytes[T ~[]byte | ~string] helper that accepts both raw bytes and strings.
| Term in the constraint | int | type Celsius int | int64 | time.Duration |
|---|---|---|---|---|
int | Yes | No | No | No |
~int | Yes | Yes | No | No |
~int64 | No | No | Yes | Yes |
~int, ~int64 union | Yes | Yes | Yes | Yes |
fmt.Stringer | No | Only with a String method | No | Yes |
Fix / how to use it: write ~ on every term unless you have a reason to exclude named types; when a call fails with "possibly missing ~", add it to the constraint, not a conversion at the call site.
// Package constraints shows how interfaces act as constraints: type sets
// with ~T terms, comparable, methods in constraints, and the pointer-method
// pattern.
package constraints
import (
"fmt"
"strconv"
)
// Integer is a type-set constraint. Without ~ only the exact predeclared
// types would satisfy it; with ~ any type whose underlying type matches does.
type Integer interface {
~int | ~int32 | ~int64
}
// Clamp limits v to [lo, hi]. Operators < and > are allowed because every
// type in Integer's type set supports them.
func Clamp[T Integer](v, lo, hi T) T {
if v < lo {
return lo
}
if v > hi {
return hi
}
return v
}
// Index works for any comparable element type: == is allowed on T.
func Index[T comparable](xs []T, v T) int {
for i, x := range xs {
if x == v {
return i
}
}
return -1
}
// IDString combines a type set with a method: T must be an integer type
// AND have a String method.
type IDString interface {
~int64
fmt.Stringer
}
// Label calls the constraint's method and uses the integer operation.
func Label[T IDString](id T) string {
return id.String() + "#" + strconv.FormatInt(int64(id)%97, 10)
}
// OrderID satisfies IDString.
type OrderID int64
func (o OrderID) String() string { return "order-" + strconv.FormatInt(int64(o), 10) }
// Setter describes a *T with a Set method: the pointer-method pattern. It
// lets a generic function create a T and call a pointer-receiver method.
type Setter[T any] interface {
*T
Set(string) error
}
// ParseAll builds one T per input by calling (*T).Set.
func ParseAll[T any, PT Setter[T]](in []string) ([]T, error) {
out := make([]T, len(in))
for i, s := range in {
if err := PT(&out[i]).Set(s); err != nil {
return nil, fmt.Errorf("item %d: %w", i, err)
}
}
return out, nil
}
// Port has a pointer-receiver Set method.
type Port struct{ N int }
// Set parses s into the port number.
func (p *Port) Set(s string) error {
n, err := strconv.Atoi(s)
if err != nil {
return err
}
if n < 1 || n > 65535 {
return fmt.Errorf("port %d out of range", n)
}
p.N = n
return nil
}package constraints
import (
"strings"
"testing"
)
type Celsius int
func TestTildeAdmitsNamedTypes(t *testing.T) {
if got := Clamp(150, 0, 100); got != 100 {
t.Fatalf("int: %d", got)
}
// Celsius has underlying type int, so ~int admits it.
if got := Clamp(Celsius(-40), -20, 50); got != -20 {
t.Fatalf("Celsius: %d", got)
}
}
func TestComparable(t *testing.T) {
if Index([]string{"a", "b"}, "b") != 1 {
t.Fatal("string")
}
type key struct{ Tenant, ID int }
if Index([]key{{1, 2}, {3, 4}}, key{3, 4}) != 1 {
t.Fatal("struct of comparable fields is comparable")
}
// Since Go 1.20 interface types satisfy comparable; == may panic at run
// time if the dynamic types are not comparable.
if Index([]any{1, "x"}, any("x")) != 1 {
t.Fatal("any")
}
}
func TestMethodInConstraint(t *testing.T) {
got := Label(OrderID(1000))
if got != "order-1000#30" {
t.Fatalf("Label: %s", got)
}
}
func TestPointerMethodPattern(t *testing.T) {
ports, err := ParseAll[Port]([]string{"80", "443"})
if err != nil || len(ports) != 2 || ports[1].N != 443 {
t.Fatalf("ports %v err %v", ports, err)
}
_, err = ParseAll[Port]([]string{"80", "70000"})
if err == nil || !strings.Contains(err.Error(), "item 1: port 70000 out of range") {
t.Fatalf("err: %v", err)
}
}comparable and strictly comparable Must-know
In plain words: comparable is the constraint for "you may use == on it", needed for map keys and set members.
Common misunderstanding: "comparable guarantees == never panics." Since Go 1.20 an interface type such as any satisfies comparable, and comparing two interface values whose dynamic type is a slice panics: panic: runtime error: comparing uncomparable type []int. The other mistake: "[]int is comparable to nil, so it satisfies comparable." It does not: []int does not satisfy comparable.
Definition: comparable is a predeclared interface that may only be used as a constraint. Its type set is the strictly comparable types: booleans, numbers, strings, pointers, channels, and structs and arrays whose fields or elements are strictly comparable. Interfaces are comparable but not strictly comparable. The spec adds an exception: a type argument that is comparable but not strictly comparable (such as any or a struct holding an any field) still satisfies comparable, which is why map[any]V-like generic types work. The blog post that explains the change opens with "Surprisingly, before Go 1.20, some comparable types did not satisfy comparable!" Slices, maps and functions are never comparable (except with nil).
1 func Index[T comparable](s []T, v T) int { ... x == v ... }
2 Index([]string{"a"}, "a") // OK: string is strictly comparable
3 Index([][]int{{1}}, []int{1}) // compile error: []int does not satisfy comparable
4 Index([]any{1, "x"}, any("x")) // OK since Go 1.20; returns 1
5 Index([]any{[]int{1}}, any([]int{1})) // compiles; at run time:
6 // panic: runtime error: comparing uncomparable type []intReal scenario: a Set[T comparable] of tenant IDs; an LRU keyed by struct{Tenant, ID int}; a de-duplication helper Unique[T comparable] on email addresses; an event bus keyed by any where a caller once passed a slice and took down the process.
| Type argument | Satisfies comparable? | == can panic? |
|---|---|---|
int, string, *Order, chan int | Yes | No |
struct{ ID int; Name string } | Yes | No |
[4]byte | Yes | No |
any, error, fmt.Stringer | Yes, since Go 1.20 | Yes, if dynamic types are not comparable |
struct{ V any } | Yes, since Go 1.20 | Yes |
[]int, map[string]int, func() | No | Not applicable |
Fix / how to use it: prefer concrete key types (string, int64, small structs) over any for generic maps and sets; if keys come from untrusted dynamic values, convert them to a canonical string or struct key first.
cmp.Ordered and the constraints package Important
In plain words: cmp.Ordered is the standard constraint for "you may use < and > on it". It covers integers, floats and strings, and named types built on them.
Common misunderstanding: "I need golang.org/x/exp/constraints for Ordered." That package was the Go 1.18 stop-gap. Since Go 1.21 the standard library has cmp.Ordered, plus cmp.Compare, cmp.Less and cmp.Or; x/exp/constraints today defines Ordered as an alias of cmp.Ordered and still offers Signed, Unsigned, Integer, Float and Complex. A second mistake: assuming < on floats is a total order. NaN < x is false for every x; cmp.Compare treats a NaN as less than any non-NaN and equal to another NaN, so sorting with it is consistent.
Definition: cmp.Ordered is interface { ~int | ~int8 | ~int16 | ~int32 | ~int64 | ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr | ~float32 | ~float64 | ~string }. cmp.Compare[T Ordered](x, y T) int returns -1, 0 or +1; cmp.Less reports x < y with the same NaN rule; cmp.Or[T comparable](vals ...T) T returns the first non-zero argument. The built-ins min and max (Go 1.21) accept any ordered operands without importing anything.
1 slices.Sort(prices) // uses cmp.Less: NaNs sort first
2 slices.SortFunc(users, func(a, b User) int {
3 return cmp.Or(cmp.Compare(a.Last, b.Last), cmp.Compare(a.First, b.First))
4 }) // multi-key sort: first non-zero wins
5 m := max(a, b, c) // built-in, no type parameter needed
6 name := cmp.Or(flagName, envName, "default") // first non-empty stringReal scenario: sorting search results by score then by ID; picking the configured value from flag, environment or default; a generic TopN[T cmp.Ordered]; sorting floats that may contain NaN after a division by zero in a report.
| Need | Standard library (Go 1.21+) | Before Go 1.21 |
|---|---|---|
| Ordered constraint | cmp.Ordered | golang.org/x/exp/constraints.Ordered |
| Three-way compare | cmp.Compare | Hand-written |
| Integer-only constraint | Write ~int and friends, or x/exp/constraints.Integer | x/exp/constraints.Integer |
| Minimum of values | min(a, b, c) built-in | Custom generic Min |
| First non-zero | cmp.Or (Go 1.22) | Hand-written |
| Sort a slice | slices.Sort, slices.SortFunc | sort.Slice with index callbacks |
Fix / how to use it: import cmp instead of x/exp/constraints for ordering; use cmp.Compare in comparison functions so NaN behaves; define your own small Integer constraint rather than pulling an x/exp dependency for one interface.
Methods in constraints and the pointer-method pattern Important
In plain words: a method in constraint position works like a method in any interface: a constraint can demand methods, exactly like a normal interface, and can combine methods with a list of types. A special trick lets a generic function call a pointer-receiver method on a T it created itself.
Common misunderstanding: "If every type in the type set has a field Name, I can read x.Name." You cannot: x.Name undefined (type T has no field or method Name). Constraints describe methods and type sets, not fields. Second mistake: "[T Setter] lets me call (*T).Set on a T." The method set of T does not include pointer-receiver methods, so you need the PT interface{ *T; Set(string) error } pattern.
Definition: inside a generic function you may call the methods that the constraint declares. A constraint like interface { ~int64; fmt.Stringer } intersects "underlying type int64" with "has String() string". The pointer-method pattern declares two type parameters: func ParseAll[T any, PT interface{ *T; Set(string) error }](in []string) ([]T, error). PT's type set contains only *T, so PT(&out[i]) is a legal conversion and .Set is callable. Callers write ParseAll[Port](in); PT is inferred from the constraint (constraint type inference). Since Go 1.26 a constraint may also refer to the type being declared: type Adder[A Adder[A]] interface{ Add(A) A }.
1 func ParseAll[T any, PT interface{ *T; Set(string) error }](in []string) ([]T, error)
2 ParseAll[Port]([]string{"80", "443"})
3 explicit: T = Port
4 infer: PT's type set is {*T} -> PT = *Port (constraint type inference)
5 body: out := make([]Port, 2); PT(&out[0]).Set("80") // calls (*Port).Set
6 result: []Port{{80}, {443}}, nilReal scenario: decoding rows into a slice of structs whose Scan method has a pointer receiver; parsing flags into typed values with Set(string) error (the flag.Value shape); building entities in a generic repository through PT.SetID; a Validate[T Validator] helper over request DTOs.
| You want to | Constraint | Works? |
|---|---|---|
Call x.String() | fmt.Stringer | Yes |
Read field x.ID | Any constraint | No: no field constraints |
Call pointer method on a local T | PT interface{ *T; M() } plus PT(&t).M() | Yes |
Use < and call String() | interface{ ~int64; String() string } | Yes |
| Union of method interfaces | fmt.Stringer or error as a union | No: union terms cannot have methods |
| Self-referential constraint | type Adder[A Adder[A]] interface{ Add(A) A } | Yes, since Go 1.26 |
Fix / how to use it: when you need data from a field, add a method (ID() int64) or pass an accessor function func(T) int64; for pointer methods use the PT pattern and document that callers pass only T.
//go:build go1.26
// Package go126 shows two Go 1.26 additions: constraints that refer to the
// type being constrained, and the generic errors.AsType.
package go126
import (
"errors"
"io/fs"
)
// Adder may refer to itself in its own type parameter list (Go 1.26).
type Adder[A Adder[A]] interface {
Add(A) A
}
// SumAll folds values whose Add method returns the same type.
func SumAll[A Adder[A]](zero A, xs ...A) A {
acc := zero
for _, x := range xs {
acc = acc.Add(x)
}
return acc
}
// Money adds to Money.
type Money struct{ Cents int64 }
// Add returns the sum.
func (m Money) Add(o Money) Money { return Money{m.Cents + o.Cents} }
// MissingPath extracts the path from a wrapped *fs.PathError without a
// pre-declared target variable.
func MissingPath(err error) (string, bool) {
if pe, ok := errors.AsType[*fs.PathError](err); ok {
return pe.Path, true
}
return "", false
}//go:build go1.26
package go126
import (
"fmt"
"os"
"testing"
)
func TestSelfReferentialConstraint(t *testing.T) {
got := SumAll(Money{}, Money{150}, Money{50})
if got.Cents != 200 {
t.Fatalf("got %d", got.Cents)
}
}
func TestAsType(t *testing.T) {
_, err := os.Open("/definitely/missing/file.txt")
wrapped := fmt.Errorf("load config: %w", err)
if p, ok := MissingPath(wrapped); !ok || p != "/definitely/missing/file.txt" {
t.Fatalf("got %q %v", p, ok)
}
if _, ok := MissingPath(fmt.Errorf("plain")); ok {
t.Fatal("no PathError in chain")
}
}Type inference and explicit instantiation Must-know
In plain words: usually you call a generic function like any other and the compiler works out the types from your arguments. When it cannot, you write the types in square brackets yourself.
Common misunderstanding: "Inference looks at the return type." It does not use the result you assign to in a call: x := Zero() fails with in call to Zero, cannot infer T (declared at ...). Since Go 1.21 inference does use the target type when an uncalled generic function is assigned to a variable of function type (var f func(int) int = Double), and Go 1.27 generalised this to every assignment or conversion context.
Definition: type inference uses function argument types, untyped constants (typed arguments take precedence; constants of different kinds such as 1 and 2.5 unify like constant expressions, giving float64), core types of constraints (the PT interface{ *T } case, S ~[]E), methods when a value is assigned to an interface (Go 1.21), and assignment context for uncalled generic functions. Explicit instantiation lists type arguments in order; you may give a prefix and let the rest be inferred: Map[string](names, strings.ToUpper). Instantiating without calling, MaxOf[int], produces an ordinary function value. A generic function cannot be used as a value without instantiation unless the context fixes its type.
1 Max(1, 2) -> T = int (untyped constants default)
2 Max(1, 2.5) -> T = float64 (constant kinds unify)
3 Max(int64(1), 2) -> T = int64 (typed argument wins)
4 Zero() -> in call to Zero, cannot infer T
5 Zero[int]() -> explicit instantiation
6 f := MaxOf[int] -> f has type func([]int) (int, bool)
7 var g func([]int) (int, bool) = MaxOf -> inferred from assignment (Go 1.21+)Real scenario: slices.IndexFunc(users, isAdmin) where isAdmin is itself generic; ParseAll[Port](raw) with the pointer type inferred; a handler table map[string]func([]byte) (any, error) filled with instantiated decoders; New[string, int](64, nil) for an LRU whose types cannot be inferred from the arguments.
| Situation | Inferred? | Write |
|---|---|---|
| Type parameter used in a parameter | Yes | Map(xs, f) |
| Type parameter only in the result | No | Zero[int]() |
| Only some inferable | Partly | Map[string](xs, f) (prefix) |
| Pointer-method pattern | Yes, from constraint | ParseAll[Port](in) |
| Uncalled function assigned to typed variable | Yes (1.21, generalised 1.27) | var f func(int) int = Double |
| Constructor with nil callbacks | No | New[string, int](64, nil) |
Fix / how to use it: order type parameters so the non-inferable ones come first; keep a parameter of type T in signatures when callers should not need brackets; read "cannot infer" as "add the first type argument explicitly".
The zero value of T Must-know
In plain words: when a generic function has nothing to return, it returns "the empty value" of whatever T is: 0, "", nil, or an empty struct.
Common misunderstanding: "I can return nil for any T." nil is only a value of pointer, slice, map, channel, function and interface types; for T any the compiler rejects return nil with cannot use nil as T value in return statement. Also "zero means invalid": 0 might be a legal value, which is why containers return (T, bool).
Definition: var zero T declares a variable initialised to T's zero value. *new(T) is the expression form. A named result (v T, ok bool) starts as the zero value and a bare return v, false works. Comparing with the zero value needs comparable (v == zero); for any, use a flag or reflect.ValueOf(&v).Elem().IsZero() only when unavoidable. Go 1.26 extended new to accept an expression (new(yearsSince(born))); that is about initial values, not generics, but makes Ptr-style helpers unnecessary for many optional fields.
1 func Pop[T any](s *Stack[T]) (T, bool) {
2 var zero T // int -> 0, string -> "", *User -> nil, struct -> all fields zero
3 if len(s.items) == 0 {
4 return zero, false // caller checks ok, never compares with zero
5 }
6 ...
7 }Real scenario: Cache.Get on a miss; First[T] on an empty slice; Load() before the first configuration snapshot; a Must[T](v T, err error) T helper in test code.
| T | var zero T | Usable as "missing"? |
|---|---|---|
int, float64 | 0 | No, 0 is a real value |
string | "" | Sometimes |
*User, []T, map[K]V | nil | Usually |
struct{...} | All fields zero | Rarely |
time.Time | 0001-01-01 00:00:00 UTC | Use IsZero() |
any | nil interface | Yes, but cannot compare generically without comparable |
Fix / how to use it: return (T, bool) or (T, error); use var zero T near the top of functions with several early returns; do not invent an Option[T] type unless the codebase already uses one (see data structures).
Generic data structures: Stack, Set, LRU, Option and Result Important
In plain words: containers are the textbook case for generics. Write the stack, set or cache once; every user gets a typed version with no assertions.
Common misunderstanding: "Generics mean I should port Rust's Option<T> and Result<T, E>." The Go convention stays (T, bool) and (T, error); the standard library's generic APIs (slices.BinarySearch, iter.Pull's next, errors.AsType) all return the comma-ok form. A wrapper type adds an allocation-free but unfamiliar layer that every caller must unwrap. Another: "container/list is generic now." It still stores any.
Definition: a generic container is a generic type whose methods do not depend on the element type beyond the constraint: Stack[T any], Set[T comparable] (map[T]struct{}), LRU[K comparable, V any] (map plus doubly linked list of typed nodes). Operations that need more than the type's constraint (for example Sorted, which needs cmp.Ordered while Set only needs comparable) become package-level functions, or, since Go 1.27, generic methods only if they add new type parameters; a method cannot tighten the receiver's constraint.
LRU capacity 2 list (most recent first) map
1 Put(a,1) a {a}
2 Put(b,2) b a {a b}
3 Get(a) a b {a b} // move to front
4 Put(c,3) c a {a c} // evict tail b, onEvict(b,2)
5 Get(b) -> zero V, falseReal scenario: an in-process LRU of rendered product pages keyed by struct{SKU string; Locale string}; a Set[Permission] checked on every request; a Stack[Frame] in an expression evaluator; a typed priority queue of retry jobs ordered by next-attempt time.
| Structure | Constraint | Standard library equivalent | Notes |
|---|---|---|---|
| Stack | T any | Slice plus append | Clear popped slots |
| Set | T comparable | map[T]struct{} | No stdlib Set type yet |
| LRU | K comparable, V any | None | Lock or shard; evict callback |
| Linked list | T any | container/list (stores any) | Write a typed one when needed |
| Heap / priority queue | T any plus less func(T, T) bool | container/heap (interface-based) | Pass the comparison function |
| Option | Convention: (T, bool) | Map lookups, Pop | Avoid exotic wrappers |
| Result | Convention: (T, error) | Everywhere | errors.AsType for typed inspection |
A generic LRU is the most useful of the three in services: the snippet below keeps typed nodes in its own doubly linked list, so neither keys nor values are boxed.
Fix / how to use it: pass comparison functions instead of requiring Less methods (the When To Use Generics advice); give containers a usable zero value or a single New; guard shared containers with a mutex and test them with -race.
// Package set is a generic set built on map[T]struct{}.
package set
import (
"cmp"
"iter"
"maps"
"slices"
)
// Set holds unique values of a comparable type.
type Set[T comparable] map[T]struct{}
// Of builds a set from values.
func Of[T comparable](vs ...T) Set[T] {
s := make(Set[T], len(vs))
for _, v := range vs {
s[v] = struct{}{}
}
return s
}
// Add inserts v and reports whether it was new.
func (s Set[T]) Add(v T) bool {
if _, ok := s[v]; ok {
return false
}
s[v] = struct{}{}
return true
}
// Has reports membership.
func (s Set[T]) Has(v T) bool { _, ok := s[v]; return ok }
// All yields the members in map order (unspecified).
func (s Set[T]) All() iter.Seq[T] { return maps.Keys(s) }
// Union returns a new set with members of both.
func Union[T comparable](a, b Set[T]) Set[T] {
out := maps.Clone(a)
if out == nil {
out = Set[T]{}
}
maps.Copy(out, b)
return out
}
// Intersect returns members present in both, iterating the smaller set.
func Intersect[T comparable](a, b Set[T]) Set[T] {
if len(a) > len(b) {
a, b = b, a
}
out := Set[T]{}
for v := range a {
if b.Has(v) {
out[v] = struct{}{}
}
}
return out
}
// Sorted returns the members in ascending order. It needs a stronger
// constraint than the type itself, so it is a function, not a method.
func Sorted[T cmp.Ordered](s Set[T]) []T {
return slices.Sorted(maps.Keys(s))
}package set
import (
"slices"
"testing"
)
func TestSet(t *testing.T) {
roles := Of("admin", "editor")
if !roles.Add("viewer") || roles.Add("admin") {
t.Fatal("Add must report novelty")
}
if !roles.Has("editor") || roles.Has("root") {
t.Fatal("Has")
}
u := Union(Of(1, 2), Of(2, 3))
if got := Sorted(u); !slices.Equal(got, []int{1, 2, 3}) {
t.Fatalf("Union = %v", got)
}
i := Intersect(Of("a", "b", "c"), Of("b", "c", "d"))
if got := Sorted(i); !slices.Equal(got, []string{"b", "c"}) {
t.Fatalf("Intersect = %v", got)
}
if n := len(slices.Collect(roles.All())); n != 3 {
t.Fatalf("All len = %d", n)
}
var nilSet Set[int]
if got := Union(nilSet, Of(7)); !got.Has(7) {
t.Fatal("Union with nil set")
}
}// Package lru is a generic, concurrency-safe least-recently-used cache.
// container/list predates generics and stores any, so the list is
// written here with typed nodes: no interface boxing, no assertions.
package lru
import "sync"
type node[K comparable, V any] struct {
key K
val V
prev, next *node[K, V]
}
// Cache maps K to V and evicts the least recently used entry when full.
type Cache[K comparable, V any] struct {
mu sync.Mutex
cap int
items map[K]*node[K, V]
head node[K, V] // sentinel: head.next is the most recent
onEvict func(K, V)
}
// New creates a cache holding at most capacity entries (minimum 1).
// onEvict may be nil; it runs with the lock held, so keep it short.
func New[K comparable, V any](capacity int, onEvict func(K, V)) *Cache[K, V] {
if capacity < 1 {
capacity = 1
}
c := &Cache[K, V]{cap: capacity, items: make(map[K]*node[K, V], capacity), onEvict: onEvict}
c.head.next, c.head.prev = &c.head, &c.head
return c
}
func (c *Cache[K, V]) unlink(n *node[K, V]) {
n.prev.next, n.next.prev = n.next, n.prev
}
func (c *Cache[K, V]) pushFront(n *node[K, V]) {
n.prev, n.next = &c.head, c.head.next
c.head.next.prev = n
c.head.next = n
}
// Get returns the value and marks it most recently used.
func (c *Cache[K, V]) Get(k K) (V, bool) {
c.mu.Lock()
defer c.mu.Unlock()
n, ok := c.items[k]
if !ok {
var zero V
return zero, false
}
c.unlink(n)
c.pushFront(n)
return n.val, true
}
// Put inserts or replaces k, evicting the oldest entry if needed.
func (c *Cache[K, V]) Put(k K, v V) {
c.mu.Lock()
defer c.mu.Unlock()
if n, ok := c.items[k]; ok {
n.val = v
c.unlink(n)
c.pushFront(n)
return
}
if len(c.items) == c.cap {
old := c.head.prev
c.unlink(old)
delete(c.items, old.key)
if c.onEvict != nil {
c.onEvict(old.key, old.val)
}
}
n := &node[K, V]{key: k, val: v}
c.items[k] = n
c.pushFront(n)
}
// Len reports the number of entries.
func (c *Cache[K, V]) Len() int {
c.mu.Lock()
defer c.mu.Unlock()
return len(c.items)
}package lru
import (
"strconv"
"sync"
"testing"
)
func TestEvictsLeastRecentlyUsed(t *testing.T) {
var evicted []string
c := New[string, int](2, func(k string, _ int) { evicted = append(evicted, k) })
c.Put("a", 1)
c.Put("b", 2)
c.Get("a") // a is now most recent
c.Put("c", 3) // evicts b
if _, ok := c.Get("b"); ok {
t.Fatal("b should be evicted")
}
if v, ok := c.Get("a"); !ok || v != 1 {
t.Fatalf("a = %d %v", v, ok)
}
if len(evicted) != 1 || evicted[0] != "b" || c.Len() != 2 {
t.Fatalf("evicted %v len %d", evicted, c.Len())
}
c.Put("a", 10) // replace keeps size
if v, _ := c.Get("a"); v != 10 || c.Len() != 2 {
t.Fatal("replace")
}
}
type userKey struct{ Tenant, ID int }
func TestStructKeysAndConcurrency(t *testing.T) {
c := New[userKey, string](64, nil)
var wg sync.WaitGroup
for g := range 8 {
wg.Add(1)
go func() {
defer wg.Done()
for i := range 200 {
k := userKey{g, i % 100}
c.Put(k, strconv.Itoa(i))
c.Get(k)
}
}()
}
wg.Wait()
if c.Len() != 64 {
t.Fatalf("len = %d", c.Len())
}
}The generic standard library Must-know
In plain words: most of the generic code you will call is already written: slices and maps for collections, cmp for ordering, sync.OnceValue for lazy values, atomic.Pointer[T] for lock-free snapshots.
Common misunderstanding: "maps.Keys returns a slice." Since Go 1.23 it returns an iter.Seq[K]; collect with slices.Collect(maps.Keys(m)) or slices.Sorted(maps.Keys(m)). The x/exp/maps.Keys you may remember returned a slice. Another: "sync.OnceValues retries after an error." It does not: the function runs once and the same value and error are returned forever.
Definition: the packages and their signatures (Go 1.27 source):
| Package | Key generic APIs | Since |
|---|---|---|
slices | Sort, SortFunc, SortStableFunc, BinarySearch, Index, IndexFunc, Contains, Equal, Clone, Compact, Insert, Delete, Reverse, Max, Min, Grow, Clip | Go 1.21 |
slices iterators | All, Values, Backward, Collect, AppendSeq, Sorted, SortedFunc, Chunk | Go 1.23 |
maps | Equal, EqualFunc, Clone, Copy, DeleteFunc | Go 1.21 |
maps iterators | All, Keys, Values, Insert, Collect | Go 1.23 |
cmp | Ordered, Compare, Less; Or | Go 1.21; Or Go 1.22 |
sync | OnceFunc, OnceValue[T], OnceValues[T1, T2] | Go 1.21 |
sync/atomic | Pointer[T] (Load, Store, Swap, CompareAndSwap) | Go 1.19 |
iter | Seq[V], Seq2[K, V], Pull, Pull2 | Go 1.23 |
errors | AsType[E error](err) (E, bool) | Go 1.26 |
math/rand/v2 | N[Int intType](n Int) Int; method (*Rand).N | Go 1.22; method Go 1.27 |
unique, weak | unique.Make[T comparable], weak.Pointer[T] | Go 1.23, Go 1.24 |
1 cfg := sync.OnceValues(loadConfig) // nothing runs yet
2 goroutine A: cfg() -> runs loadConfig, caches (*Config, nil)
3 goroutine B: cfg() -> blocks until A finishes, gets the same (*Config, nil)
4 reload: store.cur.Store(newCfg) // atomic.Pointer[Config]: readers never see a torn value
5 reader: c := store.cur.Load() // *Config, no type assertion (atomic.Value needed .(*Config))Real scenario: a handler that sorts results with slices.SortFunc and a multi-key cmp.Or; lazy parsing of a large embedded JSON file with sync.OnceValues; feature-flag snapshots swapped by a watcher goroutine into an atomic.Pointer[Flags] and read lock-free on every request; errors.AsType[*pgconn.PgError](err) in a repository.
| Old idiom | Generic replacement | Gain |
|---|---|---|
sort.Slice(s, func(i, j int) bool {...}) | slices.SortFunc(s, func(a, b T) int {...}) | Values not indexes, faster |
atomic.Value plus .(*Config) | atomic.Pointer[Config] | Typed, no assertion |
sync.Once plus package variable | sync.OnceValue(f) | Value and once in one place |
var pe *fs.PathError; errors.As(err, &pe) | pe, ok := errors.AsType[*fs.PathError](err) | No pre-declared target |
| Loop collecting map keys | slices.Sorted(maps.Keys(m)) | Deterministic order in one line |
Fix / how to use it: reach for slices/maps before writing a helper; collect iterators explicitly; treat OnceValues errors as permanent (build a new loader to retry); store immutable snapshots in atomic.Pointer and copy-on-write when updating.
// Package syncatomic shows the generic helpers in sync and sync/atomic:
// sync.OnceValue, sync.OnceValues and atomic.Pointer[T].
package syncatomic
import (
"errors"
"strings"
"sync"
"sync/atomic"
)
// Config is an immutable snapshot; a reload replaces the whole pointer.
type Config struct {
Region string
Features []string
}
// Store publishes configuration snapshots without locks on the read path.
type Store struct {
cur atomic.Pointer[Config] // typed: Load returns *Config, no assertion
}
// Load returns the current snapshot (nil before the first Swap).
func (s *Store) Load() *Config { return s.cur.Load() }
// Swap publishes c and returns the previous snapshot.
func (s *Store) Swap(c *Config) *Config { return s.cur.Swap(c) }
// UpdateRegion copies the snapshot, changes one field and publishes it
// with compare-and-swap, retrying if another writer won the race.
func (s *Store) UpdateRegion(region string) {
for {
old := s.cur.Load()
next := &Config{Region: region}
if old != nil {
next.Features = append([]string(nil), old.Features...)
}
if s.cur.CompareAndSwap(old, next) {
return
}
}
}
// NewLoader returns a function that parses raw exactly once, however many
// goroutines call it; later calls return the cached value and error.
func NewLoader(raw string, calls *atomic.Int32) func() (*Config, error) {
return sync.OnceValues(func() (*Config, error) {
calls.Add(1)
region, feats, ok := strings.Cut(raw, ";")
if !ok || region == "" {
return nil, errors.New("config: want region;feature,feature")
}
return &Config{Region: region, Features: strings.Split(feats, ",")}, nil
})
}
// Hostname is computed once on first use; sync.OnceValue has no error.
var Hostname = sync.OnceValue(func() string {
return strings.ToLower("API-1.EXAMPLE.TEST")
})package syncatomic
import (
"sync"
"sync/atomic"
"testing"
)
func TestOnceValuesRunsOnce(t *testing.T) {
var calls atomic.Int32
load := NewLoader("eu-west;search,beta", &calls)
var wg sync.WaitGroup
for range 16 {
wg.Add(1)
go func() {
defer wg.Done()
if c, err := load(); err != nil || c.Region != "eu-west" {
t.Errorf("load: %v %v", c, err)
}
}()
}
wg.Wait()
if calls.Load() != 1 {
t.Fatalf("parsed %d times", calls.Load())
}
bad := NewLoader("broken", &calls)
if _, err := bad(); err == nil {
t.Fatal("want error")
}
if _, err := bad(); err == nil || calls.Load() != 2 {
t.Fatal("error is cached too; function not re-run")
}
if Hostname() != "api-1.example.test" {
t.Fatal("OnceValue")
}
}
func TestAtomicPointerConcurrentReaders(t *testing.T) {
var s Store
if s.Load() != nil {
t.Fatal("zero Store holds nil")
}
s.Swap(&Config{Region: "eu-west", Features: []string{"search"}})
var wg sync.WaitGroup
for range 8 {
wg.Add(2)
go func() { defer wg.Done(); s.UpdateRegion("us-east") }()
go func() {
defer wg.Done()
if c := s.Load(); c == nil || len(c.Features) != 1 {
t.Errorf("torn snapshot: %+v", c)
}
}()
}
wg.Wait()
if s.Load().Region != "us-east" {
t.Fatalf("region %q", s.Load().Region)
}
}Iterators with generics: iter.Seq and iter.Pull Important
In plain words: an iterator is a function that hands values one at a time to a callback named yield. iter.Seq[T] is its generic type, and for v := range seq drives it. iter.Pull turns it into a "give me the next one" function when you need to walk two sequences side by side.
Common misunderstanding: "Ignoring yield's result is harmless." If the loop body breaks, yield returns false; an iterator that keeps calling it panics with range function continued iteration after function for loop body returned false. Second: "iter.Pull is free." It runs the sequence on a coroutine; you must call stop (usually defer stop()) if you do not drain it, and next/stop must not be called from several goroutines at once.
Definition: type Seq[V any] func(yield func(V) bool) and type Seq2[K, V any] func(yield func(K, V) bool). Generic adapters (Filter, Map, Take) take and return iter.Seq and are lazy: nothing runs until a range or slices.Collect pulls values. iter.Pull(seq) returns next func() (V, bool) and stop func(); after the end, next keeps returning the zero V and false. Range-over-func itself is covered in Functions and Control Flow; here the focus is the generic plumbing.
1 labels := Map(Take(Filter(Naturals(), even), 3), strconv.Itoa) // builds closures only
2 slices.Collect(labels)
3 Naturals yields 1 -> Filter drops
4 Naturals yields 2 -> Filter keeps -> Take #1 -> Map "2" -> collected
5 ... 4 -> "4", 6 -> "6"; Take reached 3 -> returns -> upstream yield returns false
6 result: ["2" "4" "6"]; the infinite Naturals stopped cleanlyReal scenario: streaming rows from a cursor through filters without building slices; merging two sorted feeds with iter.Pull; paging through an API with a Seq2[Item, error]; exposing All() on a custom container so callers can range it.
| Tool | Shape | Use when |
|---|---|---|
iter.Seq[V] | Push, one value | Default for exposing a sequence |
iter.Seq2[K, V] | Push, two values | Index/value, key/value, value/error |
iter.Pull | Pull, next plus stop | Zip, merge, lookahead |
| Channel plus goroutine | Push across goroutines | Real concurrency, not just sequencing |
| Slice | Materialised | Small, reused, random access |
Fix / how to use it: always check yield's result; defer stop() right after iter.Pull; prefer returning iter.Seq from methods named All, Keys, Values, matching the standard library.
// Package iterators shows generic push iterators (iter.Seq, iter.Seq2)
// and turning them into pull iterators with iter.Pull.
package iterators
import "iter"
// Filter lazily yields the values of seq for which keep is true.
func Filter[T any](seq iter.Seq[T], keep func(T) bool) iter.Seq[T] {
return func(yield func(T) bool) {
for v := range seq {
if keep(v) && !yield(v) {
return
}
}
}
}
// Map lazily transforms each value.
func Map[T, U any](seq iter.Seq[T], f func(T) U) iter.Seq[U] {
return func(yield func(U) bool) {
for v := range seq {
if !yield(f(v)) {
return
}
}
}
}
// Take yields at most n values, then stops the upstream sequence.
func Take[T any](seq iter.Seq[T], n int) iter.Seq[T] {
return func(yield func(T) bool) {
if n <= 0 {
return
}
i := 0
for v := range seq {
if !yield(v) {
return
}
i++
if i == n {
return
}
}
}
}
// Naturals is an infinite sequence 1, 2, 3, ...
func Naturals() iter.Seq[int] {
return func(yield func(int) bool) {
for i := 1; ; i++ {
if !yield(i) {
return
}
}
}
}
// Zip pairs two sequences until either ends. Two push iterators cannot be
// walked in lockstep with range, so both are converted with iter.Pull.
func Zip[A, B any](a iter.Seq[A], b iter.Seq[B]) iter.Seq2[A, B] {
return func(yield func(A, B) bool) {
nextA, stopA := iter.Pull(a)
defer stopA() // always release the pull iterator
nextB, stopB := iter.Pull(b)
defer stopB()
for {
va, okA := nextA()
vb, okB := nextB()
if !okA || !okB || !yield(va, vb) {
return
}
}
}
}package iterators
import (
"maps"
"slices"
"strconv"
"testing"
)
func TestLazyPipeline(t *testing.T) {
evens := Filter(Naturals(), func(n int) bool { return n%2 == 0 })
labels := Map(Take(evens, 3), strconv.Itoa)
if got := slices.Collect(labels); !slices.Equal(got, []string{"2", "4", "6"}) {
t.Fatalf("pipeline = %v", got)
}
}
func TestZipWithPull(t *testing.T) {
names := slices.Values([]string{"a", "b", "c"})
got := maps.Collect(Zip(names, Naturals()))
want := map[string]int{"a": 1, "b": 2, "c": 3}
if !maps.Equal(got, want) {
t.Fatalf("zip = %v", got)
}
}
func TestStdlibIterators(t *testing.T) {
m := map[string]int{"b": 2, "a": 1}
keys := slices.Sorted(maps.Keys(m))
if !slices.Equal(keys, []string{"a", "b"}) {
t.Fatalf("keys = %v", keys)
}
var idx []int
for i, v := range slices.Backward([]string{"x", "y"}) {
idx = append(idx, i)
_ = v
}
if !slices.Equal(idx, []int{1, 0}) {
t.Fatalf("backward = %v", idx)
}
chunks := slices.Collect(slices.Chunk([]int{1, 2, 3, 4, 5}, 2))
if len(chunks) != 3 || !slices.Equal(chunks[2], []int{5}) {
t.Fatalf("chunks = %v", chunks)
}
}Deconstructing type parameters: S ~[]E Important
In plain words: if your function takes a slice and returns a slice, give the whole slice type its own type parameter so a caller's named slice type comes back with its methods intact.
Common misunderstanding: "func Clone[E any](s []E) []E is the same as slices.Clone." It accepts the same arguments, but it returns []E, so an Emails value goes in and a plain []string comes out; Clone(e).Domains() stops compiling.
Definition: func Clone[S ~[]E, E any](s S) S declares S as "any type whose underlying type is a slice of E". Inference first gets S = Emails from the argument, then uses the core type of S's constraint ([]E) to infer E = string. The same idea appears as M ~map[K]V in maps. The Go blog post Deconstructing Type Parameters walks through exactly this signature.
1 type Emails []string; func (Emails) Domains() []string
2 CloneLoose(e) : E = string -> returns []string (Domains lost)
3 Clone(e) : S = Emails (argument) -> E = string (from ~[]E) -> returns Emails
4 Clone(e).Domains() // compilesReal scenario: a Dedupe over type Tags []string that must still serialise through Tags.MarshalJSON; a Filter over type Rows []Row that keeps Rows.Total(); a Merge[M ~map[K]V, K comparable, V any] over type Headers map[string]string.
| Signature | Input Emails returns | Keeps methods? |
|---|---|---|
func[E any](s []E) []E | []string | No |
func[S ~[]E, E any](s S) S | Emails | Yes |
func[M ~map[K]V, K comparable, V any](m M) M | Same map type | Yes |
func(s []string) []string (no generics) | []string | No |
Fix / how to use it: for helpers that return the collection they received, use S ~[]E / M ~map[K]V; for helpers that build a different collection, []U is fine.
// Package deconstruct shows why slices.Clone is declared
// [S ~[]E, E any]: the result keeps the caller's named slice type.
package deconstruct
// CloneLoose returns []E: a named slice type is lost on the way out.
func CloneLoose[E any](s []E) []E {
if s == nil {
return nil
}
return append([]E{}, s...)
}
// Clone returns S, so methods of a named slice type stay available.
func Clone[S ~[]E, E any](s S) S {
if s == nil {
return nil
}
return append(S{}, s...)
}
// Emails is a named slice type with a method.
type Emails []string
// Domains returns the part after @ of each address.
func (e Emails) Domains() []string {
out := make([]string, 0, len(e))
for _, a := range e {
for i := len(a) - 1; i >= 0; i-- {
if a[i] == '@' {
out = append(out, a[i+1:])
break
}
}
}
return out
}package deconstruct
import (
"slices"
"testing"
)
func TestCloneKeepsNamedType(t *testing.T) {
e := Emails{"ana@example.com", "bo@example.org"}
c := Clone(e) // S = Emails, E = string
if got := c.Domains(); !slices.Equal(got, []string{"example.com", "example.org"}) {
t.Fatalf("Domains = %v", got)
}
loose := CloneLoose(e) // type []string: loose.Domains() would not compile
if len(loose) != 2 {
t.Fatal("loose")
}
c[0] = "x@example.net"
if e[0] != "ana@example.com" {
t.Fatal("Clone must copy the backing array")
}
if Clone(Emails(nil)) != nil {
t.Fatal("nil stays nil")
}
// The standard library has the same signature.
std := slices.Clone(e)
_ = std.Domains()
}Generic type aliases Good to know
In plain words: an alias is a second name for the same type. Since Go 1.24 an alias can have its own type parameters, so type Set[T comparable] = set.Set[T] re-exports a generic type under a new package.
Common misunderstanding: "An alias creates a new type I can add methods to." It does not: Index[string] is identical to map[string][]int, and methods cannot be declared on a generic alias receiver ("alias must not be generic").
Definition: type A[P C] = T declares a generic alias; it must be instantiated when used, like a generic type. Go 1.23 shipped it as a preview behind GOEXPERIMENT=aliastypeparams (within a package only); Go 1.24 made it fully supported, and its release notes announce that the aliastypeparams opt-out setting would be removed for Go 1.25. The Go blog post What's in an (Alias) Name? explains the motivation: moving a generic type between packages without breaking callers.
1 package oldpkg: type Set[T comparable] = newpkg.Set[T] // compatibility shim
2 caller: var s oldpkg.Set[string] = newpkg.Of("a") // no conversion: identical types
3 later: delete the alias when callers have migratedReal scenario: splitting a large util package into set, lru, xslices without a flag day; giving a long instantiated type a short local name (type Index[K comparable] = map[K][]int); aligning an internal type with a generated one during a code generator upgrade.
| Declaration | New type? | Methods allowed? | Since |
|---|---|---|---|
type Cents int64 | Yes (defined type) | Yes | Go 1.0 |
type Byte = uint8 | No (alias) | Only where the original is local | Go 1.9 |
type Set[T comparable] map[T]struct{} | Yes (generic type) | Yes | Go 1.18 |
type Set[T comparable] = set.Set[T] | No (generic alias) | No | Go 1.24 |
Fix / how to use it: use generic aliases for migrations and short names, not to model new concepts; add a // Deprecated: comment on the shim.
// Package aliases shows generic type aliases (Go 1.24): an alias with its
// own type parameters that denotes another, possibly generic, type.
package aliases
import "academy/generics/set"
// Set re-exports set.Set under this package's name during a migration.
// Before Go 1.24 an alias could not declare type parameters.
type Set[T comparable] = set.Set[T]
// Index is a generic alias for a map type; Index[string] is identical to
// map[string][]int, not a new named type.
type Index[K comparable] = map[K][]int
// Build records the positions where each word occurs.
func Build[K comparable](words []K) Index[K] {
idx := Index[K]{}
for i, w := range words {
idx[w] = append(idx[w], i)
}
return idx
}package aliases
import (
"slices"
"testing"
"academy/generics/set"
)
func TestAliasesAreIdenticalTypes(t *testing.T) {
var s Set[string] = set.Of("a") // no conversion: same type
s.Add("b")
var direct set.Set[string] = s
if !direct.Has("b") {
t.Fatal("alias and original are one type")
}
var m map[string][]int = Build([]string{"go", "php", "go"})
if !slices.Equal(m["go"], []int{0, 2}) {
t.Fatalf("index = %v", m)
}
}Generic methods (Go 1.27) and generic interfaces Important
In plain words: from Go 1.27 a method can introduce its own type parameters, so list.Map(f) can return a list of a different element type. Interfaces can be generic too (type Getter[T any] interface{ Get() T }), but an interface method still cannot have type parameters.
Common misunderstanding: "Now a generic method can satisfy an interface." It cannot. The Go 1.27 release notes: "methods of interfaces may not declare type parameters nor can interface methods be implemented by generic methods." A type whose only Map is generic does not implement interface{ Map(func(int) int) []int }: the compiler reports wrong type for method Map with have Map[F any](func(int) F) []F / want Map(func(int) int) []int. Also, in a module whose go.mod says go 1.24, a generic method fails with generic method requires go1.27 or later (-lang was set to go1.24; check go.mod).
Definition: a method declaration may list type parameters after the method name, in addition to those declared by the receiver: func (l List[E]) Map[F any](f func(E) F) List[F]. "Like a generic function, a generic method must be instantiated before it can be called or used as a value"; inference works as for functions, and explicit instantiation is l.Map[string](f). A generic interface is an interface type with type parameters (Getter[T]); it is instantiated like any generic type and can be implemented by ordinary methods (func (c Conf) Get() string implements Getter[string]). Interface methods with their own type parameters are rejected: interface method must have no type parameters. Because interface satisfaction never involves generic methods, the runtime never has to instantiate a method on demand, which was the FAQ's objection.
1 go.mod: go 1.24, file without build tag: func (l List[E]) Map[F any](...) -> generic method requires go1.27 or later
2 file with //go:build go1.27 (or go.mod go 1.27): compiles with a 1.27+ toolchain
3 words.Filter(long).Map(strlen) // F = int inferred
4 words.Map[string](strings.ToUpper) // explicit method instantiation
5 var _ Mapper = L{} // L does not implement Mapper (wrong type for method Map)Real scenario: fluent query builders that change the row type (q.Select[Summary](...)); a Result[T].Map[U]-style helper in a codebase that already uses wrappers; (*rand.Rand).N in math/rand/v2 (Go 1.27) so seeded generators get the same generic helper as the package function; typed Getter[T] interfaces for configuration sources.
| Feature | Go 1.18 to 1.26 | Go 1.27 |
|---|---|---|
| Generic type with methods | Yes | Yes |
| Method declaring its own type parameters | No | Yes |
| Interface method with type parameters | No | No |
| Generic method implementing an interface method | Not applicable | No |
Generic interface type Getter[T] | Yes | Yes |
Per-file opt-in from an older go.mod | Not applicable | //go:build go1.27 |
Fix / how to use it: keep helpers that must satisfy interfaces non-generic; use generic methods for fluent, chainable APIs; gate the file with //go:build go1.27 (as the snippet does) or raise the module's go line when every consumer runs Go 1.27.
//go:build go1.27
// Package genericmethod shows Go 1.27 generic methods: a method may declare
// its own type parameters in addition to the receiver's. The build
// constraint raises this file's language version above the module's go
// 1.24 line, and older toolchains skip the file.
package genericmethod
// List is a slice with chainable helpers.
type List[E any] []E
// Map returns a List of another element type. Before Go 1.27 this had to
// be a package-level function Map[E, F any](l List[E], f func(E) F).
func (l List[E]) Map[F any](f func(E) F) List[F] {
out := make(List[F], len(l))
for i, x := range l {
out[i] = f(x)
}
return out
}
// Filter needs no extra type parameter; it is an ordinary method.
func (l List[E]) Filter(keep func(E) bool) List[E] {
var out List[E]
for _, x := range l {
if keep(x) {
out = append(out, x)
}
}
return out
}//go:build go1.27
package genericmethod
import (
"slices"
"strings"
"testing"
)
func TestGenericMethodChain(t *testing.T) {
words := List[string]{"go", "php", "rust"}
lens := words.Filter(func(s string) bool { return len(s) > 2 }).Map(func(s string) int { return len(s) })
if !slices.Equal(lens, List[int]{3, 4}) {
t.Fatalf("lens = %v", lens)
}
// Explicit instantiation of the method's own type parameter.
up := words.Map[string](strings.ToUpper)
if up[0] != "GO" {
t.Fatalf("up = %v", up)
}
}GC shape stenciling and dictionaries Important
In plain words: the compiler does not write a fresh copy of the function for every type you use, and it does not compile one fully dynamic version either. It groups types by "shape" and writes one copy per group, passing a small table of type information along.
Common misunderstanding: "Generics are monomorphised like C++ templates or Rust, so they are always as fast as hand-written code." gc's design note: "Two concrete types are in the same gcshape grouping if and only if they have the same underlying type or they are both pointer types." So every pointer type shares one body, and a method call through a pointer-shaped type parameter goes through the dictionary: an indirect call that is usually not inlined. There is no user-visible specialization: you cannot write a faster body for T = int.
Definition: stenciling means generating a copy of a generic function for type arguments; GC shape stenciling generates one shape instantiation per GC shape (named like Id[go.shape.int], Id[go.shape.string], Id[go.shape.*uint8]). A dictionary is a static, read-only table per instantiation site (named like ..dict.Id[*int]) holding runtime type descriptors, sub-dictionaries and method entries; it is passed as a hidden argument. The FAQ is deliberately non-committal: the compiler "can choose whether to compile each instantiation separately or whether to compile similar instantiations as a single implementation", and the standard compiler "ordinarily emits a single instantiation for every type argument with the same shape". Wrapper functions named after the concrete type (Id[*int]) exist for function values and reflection; they call the shape body with the dictionary.
1 source: Id(1); Id("s"); Id(&A{}); Id(new(int))
2 shapes: go.shape.int, go.shape.string, go.shape.*uint8 (shared by *A and *int)
3 dicts: ..dict.Id[int], ..dict.Id[string], ..dict.Id[*A], ..dict.Id[*int]
4 call: Id[go.shape.*uint8](dict=&..dict.Id[*A], x)
5 in body: x.Value() on a pointer shape -> load method from dict -> indirect callReal scenario: a generic Sum over []int runs as fast as the hand-written loop (no method calls, the shape is int); a generic TotalGeneric[T Valuer] over []*Item runs at interface-call speed because *Item is pointer-shaped; a hot path that called x.Hash() through a type parameter showed no gain over Hasher interfaces; binary size grows less than with full monomorphisation.
| Implementation strategy | Used by | Code size | Speed of method calls on T |
|---|---|---|---|
| Full monomorphisation | C++ templates, Rust | Largest | Direct, inlinable |
| Type erasure | Java | Smallest | Virtual call, boxed values |
| GC shape stenciling plus dictionaries | Go gc (since 1.18) | Medium | Direct for operators on value shapes; indirect for methods on pointer shapes |
| Interface values | Go without generics | Small | Indirect (itab) |
Fix / how to use it: do not convert interfaces to type parameters for speed; measure with benchmarks (see the Lab: concrete 259 ns, generic 251 ns, []any 317 ns; interface method 833 ns, generic method 786 ns on 1024 elements); keep hot loops over value types (int, float64, small structs) where shapes are specific; inspect with go build -gcflags=-S and look for go.shape symbols.
// Package bench compares a concrete loop, a generic loop and an
// interface-based loop, and a generic method call through a constraint.
package bench
// Number is the constraint used by SumGeneric.
type Number interface{ ~int | ~int64 | ~float64 }
// SumConcrete is the hand-written int version.
func SumConcrete(xs []int) int {
var s int
for _, x := range xs {
s += x
}
return s
}
// SumGeneric is instantiated for the GC shape of T (here: int).
func SumGeneric[T Number](xs []T) T {
var s T
for _, x := range xs {
s += x
}
return s
}
// SumAny boxes every element and asserts it back.
func SumAny(xs []any) int {
var s int
for _, x := range xs {
s += x.(int)
}
return s
}
// Valuer is used both as an interface and as a constraint.
type Valuer interface{ Value() int }
// Item implements Valuer with a pointer receiver.
type Item struct{ v int }
// Value returns the stored number.
func (i *Item) Value() int { return i.v }
// TotalIface calls Value through an interface.
func TotalIface(xs []Valuer) int {
var s int
for _, x := range xs {
s += x.Value()
}
return s
}
// TotalGeneric calls Value through a type parameter. Every pointer type
// shares one GC shape, so the call goes through the dictionary.
func TotalGeneric[T Valuer](xs []T) int {
var s int
for _, x := range xs {
s += x.Value()
}
return s
}package bench
import "testing"
const n = 1024
func ints() []int {
xs := make([]int, n)
for i := range xs {
xs[i] = i
}
return xs
}
func TestSumsAgree(t *testing.T) {
xs := ints()
boxed := make([]any, n)
items := make([]*Item, n)
ifaces := make([]Valuer, n)
for i, x := range xs {
boxed[i] = x
items[i] = &Item{x}
ifaces[i] = items[i]
}
want := SumConcrete(xs)
if SumGeneric(xs) != want || SumAny(boxed) != want ||
TotalIface(ifaces) != want || TotalGeneric(items) != want {
t.Fatal("implementations disagree")
}
}
var sink int
func BenchmarkSumConcrete(b *testing.B) {
xs := ints()
for b.Loop() {
sink = SumConcrete(xs)
}
}
func BenchmarkSumGeneric(b *testing.B) {
xs := ints()
for b.Loop() {
sink = SumGeneric(xs)
}
}
func BenchmarkSumAny(b *testing.B) {
xs := make([]any, n)
for i := range xs {
xs[i] = i
}
for b.Loop() {
sink = SumAny(xs)
}
}
func BenchmarkTotalIface(b *testing.B) {
xs := make([]Valuer, n)
for i := range xs {
xs[i] = &Item{i}
}
for b.Loop() {
sink = TotalIface(xs)
}
}
func BenchmarkTotalGeneric(b *testing.B) {
xs := make([]*Item, n)
for i := range xs {
xs[i] = &Item{i}
}
for b.Loop() {
sink = TotalGeneric(xs)
}
}Limitations Important
In plain words: Go generics deliberately stop short of what some languages offer. Knowing the edges saves hours of fighting the compiler.
Common misunderstanding: "A type switch on T is the way to specialise." switch x.(type) on a type parameter value is rejected: cannot use type switch on type parameter value x (variable of type T constrained by any). You can convert first (switch any(x).(type)), but then you have written reflection-style code with extra steps; if behaviour differs per type, the official advice is an interface.
Definition: the current limits, with the version that changed each one:
| Limitation | Status in Go 1.27 | Workaround |
|---|---|---|
| Methods with type parameters (the old rule: no methods with type params) | Allowed since Go 1.27; not in interfaces, cannot implement interface methods | Package-level function before 1.27 |
| Generic type aliases | Allowed since Go 1.24 | Defined type before 1.24 |
| Specialization (a different body for one type argument) | Not supported | Separate function, or any(x).(type) |
Higher-kinded types (a type parameter that is itself generic, such as F[_]) | Not supported | Pass functions; instantiate concrete types |
Field access through a constraint (x.Name) | Not supported | Method or accessor function |
| Type switch directly on a type parameter value | Not supported | switch any(x).(type) |
| Variadic type parameters | Not supported | Fixed arity or any |
| Operator overloading | Not supported | Methods (Add), self-referential constraint (1.26) |
| Union terms with methods | Not supported | Two constraints or a method-only interface |
| Embedding a type parameter in a struct | Not supported | Named field v T |
| Type parameter as RHS of a type declaration | Not supported | Struct wrapper |
Covariance ([]Cat as []Animal) | Not supported | Convert element-wise |
| Self-reference in a type parameter list | Allowed since Go 1.26 | Helper interface before 1.26 |
| Type declarations inside generic functions | Allowed since Go 1.20 (Go 1.18 limitation lifted) | Move to package level on 1.18/1.19 |
1 func Kind[T any](x T) string { switch x.(type) { ... } } // cannot use type switch on type parameter value x
2 func Kind[T any](x T) string { switch any(x).(type) { ... } } // compiles; runtime dispatch, no specialization
3 func Name[T P](x T) string { return x.Name } // x.Name undefined (type T has no field or method Name)
4 type Visitor interface{ Visit[T any](T) } // interface method must have no type parametersReal scenario: an attempt to write Functor[F[_]] for a functional-style library fails immediately; a generic repository that wanted x.ID ends up requiring an ID() int64 method; a JSON helper that type-switched on T was rewritten with encoding/json (reflection) because behaviour truly differed per type.
Fix / how to use it: when a limitation blocks you, it is usually a sign that an interface, a function argument or reflection fits better; check the Go version before assuming a limitation still applies (1.24 aliases, 1.26 self-reference, 1.27 methods).
When to use generics (and when over-abstraction hurts) Must-know
In plain words: start with ordinary code. Add a type parameter when you notice you are about to write the same code again for a different type.
Common misunderstanding: "Generic is more reusable, so more generic is better." Generic signatures are harder to read, error messages get longer, and a Repository[T Entity, ID comparable, F Filter[T]] couples every module to one abstraction. The Go blog: "If all you need to do with a value of some type is call a method on that value, use an interface type, not a type parameter."
Definition: Ian Lance Taylor's guidelines (When To Use Generics, 2022): type parameters are useful for functions on language-defined containers (slices, maps, channels) that make no assumptions about the element type; for general-purpose data structures; for methods whose implementation is the same for all types; and you should prefer functions (comparison callbacks) to method constraints. They are not useful when you only call methods (use an interface), when implementations differ per type (interface), or when the operation must work on types without methods and differs per type (reflection, as encoding/json does). The closing rule: "avoid type parameters until you notice that you are about to write the exact same code multiple times."
1 week 1: func SumOrders(xs []Order) Money // concrete
2 week 3: func SumRefunds(xs []Refund) Money // same loop, other type -> now consider generics
3 option: func SumBy[T any](xs []T, amount func(T) Money) Money
4 reject: type Summable interface{ Amount() Money }; func Sum[T Summable](xs []T) // only calls a method -> interface
5 result: SumBy for slices of different types; no new constraint typesReal scenario: a team replaced fifteen ContainsX helpers with slices.Contains; another wrapped every service in Service[Req, Resp] and found that stack traces, mocks and docs all became harder to read; a func Handle[T io.Reader](r T) was reverted to io.Reader with no performance change.
| Signal | Over-abstraction | Healthy |
|---|---|---|
| Type parameters per signature | Three or more, nested constraints | One or two |
| Constraint declares only methods | [T Saver] | s Saver parameter |
| Number of instantiations | One | Several |
| Reader effort | Needs the constraint's definition to understand the call | Obvious from the call |
| Error messages | Mention instantiated names and constraints | Plain types |
Fix / how to use it: apply the decision diagram above; keep generic code in leaf utility packages; refuse generic "base" types for business entities.
Tooling: go vet and gopls Good to know
In plain words: the usual tools understand generics: go vet checks generic code as if each permitted type were substituted, and gopls shows inferred type arguments.
Common misunderstanding: "vet cannot see through T." Since Go 1.18 vet reports a problem in generic code whenever it would report it for the non-generic equivalent with some type from the type set. A Printf("%d", t) with T ~int | ~string is flagged because T may be a string.
Definition: vet's printf check prints fmt.Printf format %d has arg t of wrong type T (contains ~string). gopls hover shows the instantiated signature at a call site; the functionTypeParameters inlay hint (off by default, "hints": {"functionTypeParameters": true}) renders inferred type arguments inline as myFoo«[int, string]»(1, "hello"); rename and find-references work across instantiations. go doc prints generic signatures (func Pull[V any](seq Seq[V]) (next func() (V, bool), stop func())).
1 write: func Print[T ~int | ~string](t T) { fmt.Printf("%d\n", t) }
2 go vet: fmt.Printf format %d has arg t of wrong type T (contains ~string)
3 fix: use %v, or narrow the constraint to ~intReal scenario: a logging helper Debugf[T any] that vet now checks like Printf; a code review where the inlay hint showed Map«[Row, DTO]» and revealed an unintended type; a refactor renaming a constraint across fifty call sites with gopls.
| Tool | Generic support |
|---|---|
go vet | Checks every type in the type set (printf, copylocks, others) |
gopls hover | Instantiated signature at call site |
gopls inlay hints | functionTypeParameters shows inferred type arguments |
go doc | Prints type parameter lists and constraints |
| Stack traces | Generic frames printed as main.Index[...](...) |
go build -gcflags=-S | Shows shape instantiations and dictionaries |
Fix / how to use it: run go vet ./... in CI; enable the inlay hint while learning; read [...] in stack traces as "a generic function, see the source for its type arguments".
Go
Before
Before generics a Go codebase either repeated a loop for every numeric type or stored values in interface{} containers and asserted them back. Both compile; one repeats itself, the other moves type errors to run time.
// Package before shows the two pre-generics habits: one copy of the same
// code per element type, and containers of interface{} that push type
// checks to run time.
package before
// SumInts adds int values.
func SumInts(xs []int) int {
var s int
for _, x := range xs {
s += x
}
return s
}
// SumFloats is the same loop again, only the type differs.
func SumFloats(xs []float64) float64 {
var s float64
for _, x := range xs {
s += x
}
return s
}
// Stack stores anything; callers must assert the type they expect.
type Stack struct {
items []interface{}
}
// Push adds v on top.
func (s *Stack) Push(v interface{}) { s.items = append(s.items, v) }
// Pop removes and returns the top value, or nil when empty.
func (s *Stack) Pop() interface{} {
if len(s.items) == 0 {
return nil
}
v := s.items[len(s.items)-1]
s.items = s.items[:len(s.items)-1]
return v
}package before
import "testing"
func TestDuplicatedSums(t *testing.T) {
if got := SumInts([]int{1, 2, 3}); got != 6 {
t.Fatalf("SumInts = %d", got)
}
if got := SumFloats([]float64{1.5, 2.5}); got != 4 {
t.Fatalf("SumFloats = %v", got)
}
}
func TestInterfaceStackNeedsAssertions(t *testing.T) {
var s Stack
s.Push(1)
s.Push("two") // compiles: nothing stops mixing types
if _, ok := s.Pop().(int); ok {
t.Fatal("top is a string, the int assertion must fail")
}
n, ok := s.Pop().(int)
if !ok || n != 1 {
t.Fatalf("got %v, %v", n, ok)
}
if s.Pop() != nil {
t.Fatal("empty stack returns nil")
}
}After
The after package (shown under Constraints) replaces both with Sum[T Number] and Stack[T any]: one copy of each, checked at compile time, accepting named types such as Cents through ~int64. The whole module runs with:
cd docs/snippets/go/generics/go
gofmt -l . && go vet ./... && go test -race ./...module academy/generics
go 1.24The Go angle
Go's generics are intentionally small: constraints are interfaces, there is no variance, no specialization, no higher-kinded types, and inference never looks at a call's result type. The standard library adopted them carefully: slices, maps, cmp, iter, sync.OnceValue, atomic.Pointer and errors.AsType are generic; io.Reader, http.Handler, sort.Interface and context.Context stay interfaces because their callers only call methods. The gc compiler's GC shape stenciling keeps binaries and compile times moderate at the price of indirect method calls for pointer shapes. Version gating is part of daily work: aliases need 1.24, self-referential constraints 1.26, generic methods 1.27; a file-level //go:build go1.27 lets one file use the newer language while the module stays on go 1.24.
For PHP/Laravel developers
PHP has no runtime generics. Static analysers (PHPStan, Psalm) and IDEs read the @template docblock (a template docblock declares a type variable) and check them before the code runs; PHP itself ignores them. Laravel's own collections are annotated this way (Collection<TKey, TValue>), which is why $users->map(...) autocompletes in an IDE.
| PHP (PHPStan docblocks) | Go | Difference |
|---|---|---|
@template T on a function or class | [T any] | Go checks at compile time and rejects bad calls; PHP only warns in the analyser |
@template T of \Countable (upper bound) | [T Countable] constraint | Go constraints can also be type sets (~int) |
@template T = string (default) | No defaults | Go type arguments are inferred or explicit, never defaulted |
@param class-string<T> $class | Explicit instantiation New[T]() | Go needs no class-name string |
@template-covariant T | No variance | Stack[Cat] is never a Stack[Animal] |
@extends Collection<int, User> | Instantiation Collection[int, User] | Go has no inheritance; embed or wrap |
array<int, User>, list<User> | map[int]User, []User | Built into Go's types |
| Runtime: plain arrays and objects | Runtime: unboxed typed values | Go stores the real type |
<?php
/**
* @template T
* @param list<T> $items
* @param callable(T): bool $keep
* @return list<T>
*/
function filter(array $items, callable $keep): array
{
return array_values(array_filter($items, $keep));
}
/** @var list<int> $even */
$even = filter([1, 2, 3, 4], fn (int $n): bool => $n % 2 === 0);
// PHPStan knows $even is list<int>; PHP itself would accept filter(['a'], ...) at run time.The Go equivalent is basics.Filter above: the same signature, but checked by the compiler on every build and executed with unboxed int values. Where Laravel uses a container or facade to resolve "a thing of class X" at run time, Go code passes the concrete type as a type argument or, more often, a constructor function.
Mechanics
What the compiler does with generic code
| Step | What happens | Observable through |
|---|---|---|
| 1. Parse | [T C] lists parsed without type information (why Go uses brackets, not angle brackets) | Syntax errors only |
| 2. Type-check generic body | Body checked once against constraints; only operations of every type in the type set allowed | invalid operation: a > b (type parameter T cannot use operator >) |
| 3. Infer | Explicit prefix, then function arguments, untyped constants, constraint core types, assignment context | cannot infer T |
| 4. Instantiate | Substitute type arguments, then verify each satisfies its constraint | X does not satisfy C (...) |
| 5. Shape | Group type arguments by GC shape, create shape instantiation once per package build | go.shape.* symbols |
| 6. Dictionary | Emit static dictionary per call site's concrete type arguments; linker dedupes | ..dict.F[T] symbols |
| 7. Wrappers | Concrete-named wrappers for function values and reflection | F[*int] STEXT WRAPPER |
Exact messages
All messages below were produced with Go 1.27.4 in a scratch module (go 1.24 in go.mod) by go build; file positions are trimmed.
| Situation | Message |
|---|---|
| Non-comparable type argument | []int does not satisfy comparable |
| Generic type used bare | cannot use generic type Stack[T any] without instantiation |
| Type parameter only in result | in call to Zero, cannot infer T (declared at e3/m.go:3:11) |
Named type, constraint without ~ | MyInt does not satisfy Number (possibly missing ~ for int in Number) |
| Type outside the union | string does not satisfy int or float64 (string missing in int or float64), printed with vertical bars |
| Missing method | int does not satisfy fmt.Stringer (missing method String) |
| Operator not in every type | invalid operation: a > b (type parameter T cannot use operator >) |
| Constraint used as a variable type | cannot use type Number outside a type constraint: interface contains type constraints |
| Field through a type parameter | x.Name undefined (type T has no field or method Name) |
| Type switch on a type parameter | cannot use type switch on type parameter value x (variable of type T constrained by any) |
| Type parameter as whole type | cannot use a type parameter as RHS in type declaration |
| Interface method with type parameters | interface method must have no type parameters |
| Generic method under old language version | generic method requires go1.27 or later (-lang was set to go1.24; check go.mod) |
| Generic method against interface | L does not implement Mapper (wrong type for method Map) / have Map[F any](func(int) F) []F / want Map(func(int) int) []int |
| vet printf in generic code | fmt.Printf format %d has arg t of wrong type T (contains ~string) |
Runtime: == on any holding a slice | panic: runtime error: comparing uncomparable type []int |
Runtime: iterator ignores yield false | panic: runtime error: range function continued iteration after function for loop body returned false |
Flags and settings
| Knob | Effect |
|---|---|
go 1.18 or later in go.mod | Enables type parameters for the module |
go 1.24 in go.mod | Generic type aliases |
go 1.27 in go.mod, or //go:build go1.27 in a file | Generic methods for the module or file |
go build -gcflags=-S | Assembly listing: go.shape instantiations, ..dict symbols |
go build -gcflags=-m | Inlining decisions, including of shape instantiations |
go test -bench . -benchmem | Compare generic, interface and concrete versions |
GOEXPERIMENT=aliastypeparams | Go 1.23 preview of generic aliases; Go 1.24 notes say the setting goes away for Go 1.25 |
gopls "hints": {"functionTypeParameters": true} | Show inferred type arguments |
go vet ./... | Generic-aware analyzers |
Solving the classic problems
| Problem | Solution | How | Advantage | Cost or limit |
|---|---|---|---|---|
| Same loop per numeric type | Type-set constraint | Sum[T Number] with ~ terms | One copy, named types accepted | Constraint to maintain |
interface{} container with assertions | Generic type | Stack[T any] | Compile-time safety, no boxing | Each instantiation is a distinct type |
| Named slice type loses methods | Deconstruct | [S ~[]E, E any] | Returns the caller's type | Two type parameters |
Need a pointer method on a created T | Pointer-method pattern | PT interface{ *T; M() } | Works with value slices | Harder to read |
| Sort or compare in a container | Function argument | less func(T, T) bool or cmp func(T, T) int | Works for int without wrapper types | Extra parameter |
| Typed lazy value | sync.OnceValue(s) | var cfg = sync.OnceValues(load) | Once and value together | Errors cached forever |
| Typed hot-swappable snapshot | atomic.Pointer[T] | Store/Load/CompareAndSwap | Lock-free reads | Immutable snapshots only |
| Inspect error type | errors.AsType | pe, ok := errors.AsType[*fs.PathError](err) | No pre-declared target | Go 1.26+ |
| Walk two sequences together | iter.Pull | next, stop := iter.Pull(seq); defer stop() | Zip, merge | Coroutine overhead; single goroutine |
| Rename a generic type across packages | Generic alias | type Set[T comparable] = set.Set[T] | No breaking change | Go 1.24+ |
| Chainable transformations | Generic method | func (l List[E]) Map[F any] | Fluent API | Go 1.27+, not in interfaces |
| Per-type behaviour | Interface or reflection | Not a type switch on T | Clear dispatch | Indirect calls |
Typed lazy configuration with OnceValues and atomic.Pointer
syncatomic.NewLoader wraps the parsing in sync.OnceValues, so sixteen goroutines in the test trigger exactly one parse; Store holds an atomic.Pointer[Config] and UpdateRegion performs a copy-on-write compare-and-swap loop. The race detector runs over both in go test -race.
A generic repository: keep the SQL concrete
A common over-abstraction is Repository[T any] that builds SQL from reflection. Generics help with the plumbing (scanning rows into []T, paging, Page[T] responses) but the SQL should stay per entity, so indexes, joins and locking stay visible. The tables a typed repository would target:
CREATE TABLE orders (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
tenant_id bigint NOT NULL,
total_cents bigint NOT NULL CHECK (total_cents >= 0),
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX orders_tenant_created ON orders (tenant_id, created_at DESC, id DESC);
-- keyset page used by a generic Page[Order] helper; the query itself is written per entity
SELECT id, tenant_id, total_cents, created_at
FROM orders
WHERE tenant_id = $1 AND (created_at, id) < ($2, $3)
ORDER BY created_at DESC, id DESC
LIMIT $4;The generic part is func ScanAll[T any, PT interface{ *T; ScanFrom(Row) error }](rows Rows) ([]T, error), the same pointer-method pattern as ParseAll. Connection handling and pgx are covered in database/sql & pgx; keyset pagination in Pagination.
Choosing
| Situation | Recommendation | Extra technique | Reason |
|---|---|---|---|
| Function over slices/maps/channels of any element | Type parameter | S ~[]E when returning the input type | Same code for every element type |
| Container (stack, set, cache, tree) | Generic type | Comparison as a function field | Typed storage, no assertions |
| Only calls methods on the argument | Interface parameter | Small interface at the consumer | Simpler, same speed |
| Implementations differ per type | Interface with several implementations | Table-driven tests per implementation | Real polymorphism |
| Types without methods, behaviour per type (encoding) | Reflection | Cache reflected metadata | Generics cannot specialise |
| Arithmetic over several numeric types | Type-set constraint with ~ | cmp.Ordered for comparison only | Operators need type sets |
| Hot loop with method calls on pointer types | Concrete code or interface; measure | Benchmark with b.Loop | Pointer shapes share a body |
| Lazy value or snapshot | sync.OnceValue, atomic.Pointer[T] | Copy-on-write updates | Typed, race-free |
| Lazy sequence | iter.Seq[T] | iter.Pull for zip/merge | No goroutines, composable |
| Migration of a generic type | Generic alias | // Deprecated: on the shim | Zero breaking changes |
| Fluent API needing a new element type | Generic method (Go 1.27) | Keep interface methods non-generic | Namespaced helpers |
| One instantiation only | No generics | Wait for the second use | Avoid speculative abstraction |
In architecture: from a single process to a distributed system
Monolith (one process, one database)
Generics live in leaf packages: internal/xslices (only for what slices lacks), internal/cache with lru.Cache[K, V], internal/set. Business code stays concrete: orders.Service, orders.Repository with explicit SQL. Example: the catalogue handler keeps lru.New[catalogKey, []byte](10_000, nil) for rendered pages, slices.SortFunc with cmp.Or for multi-key sorting, and a sync.OnceValues loader for the embedded tax table. One rule keeps it healthy: a generic package never imports a business package.
Modular monolith / multiple databases
Each module owns its entities and its SQL, yet modules want shared plumbing: pagination, results, retries. Put generic building blocks in a small shared kit (kit/page.Page[T], kit/retry.Do[T]) with no dependencies on modules. Resist a shared Repository[T Entity] base: it couples every module's persistence to one abstraction and one database, which is exactly what modules with separate schemas or separate databases must avoid. When a module moves its types to a new package, a generic alias keeps the old import path compiling for one release.
Microservices
Type parameters do not cross a network boundary; the wire carries JSON or protobuf, and each service decodes into concrete types. Generics still help at the edges: a typed client helper func Call[Req, Resp any](ctx context.Context, c *http.Client, url string, req Req) (Resp, error) removes boilerplate around encoding and error mapping, and an event envelope Envelope[T any]{ID, Type, OccurredAt, Data T} gives producers and consumers a typed Data while the schema registry or Type string decides which T to decode. Example flow: orders service publishes Envelope[OrderPlaced] (JSON) -> broker -> billing consumer switches on Type, calls Decode[OrderPlaced](raw) -> handler with a typed payload. Versioning stays a wire concern (fields added compatibly), not a generics concern. Envelope and schema evolution are in Message Design & Schema Evolution; gRPC codegen in gRPC & Protobuf in Go.
Distributed data (replicas, caches, multi-region)
A generic lru.Cache[K, V] is per process: three replicas hold three different caches, and an update in one region is invisible to the others until entries expire. Use it for data where staleness is acceptable, key it by a struct that includes tenant and version (struct{Tenant int64; SKU string; Ver int}) so invalidation is a version bump, and move shared state to Redis or the database when replicas must agree (see Caching). Configuration snapshots in atomic.Pointer[Config] are swapped by a watcher (file, etcd, or a config service); readers see either the old or the new snapshot, never a mix, but two replicas may run different snapshots for a few seconds, so feature flags must tolerate that window.
Scaling path
| Scale | What changes for generics | Example |
|---|---|---|
| 1x: one service, few developers | Use stdlib generics; write few of your own | slices, maps, cmp, one Set |
| 10x: hot paths visible in profiles | Benchmark generic versus concrete for pointer-shaped method calls | Replace TotalGeneric[T Valuer] with a concrete loop in the hottest path |
| 100x: many replicas | Per-process generic caches diverge | lru.Cache as L1, Redis as L2, versioned keys |
| Many teams | Generic kit becomes a dependency of everything | Version the kit module, keep it tiny, forbid business types in it |
| Many services | Generic envelopes and clients standardise edges | Envelope[T], Call[Req, Resp], generated code for the rest |
Lab
All commands run on a laptop with Go installed; no network is needed. Output below was produced with Go 1.27.4 on macOS (arm64, Apple M4 Pro) unless labelled expected, not run.
Setup
cd docs/snippets/go/generics/go
go version
gofmt -l . && go vet ./... && go test -race ./...Output (verified): go version go1.27.4 darwin/arm64, then ok for all fourteen packages (academy/generics/after, aliases, basics, before, bench, constraints, deconstruct, genericmethod, go126, iterators, lru, set, stack, syncatomic).
Experiment 1: the instantiation errors
Create a scratch module (go mod init scratch, keep go 1.24) and paste each snippet into its own package, then go build ./...:
func Index[T comparable](s []T, v T) int { return 0 }
var _ = Index([][]int{{1}}, []int{1}) // []int does not satisfy comparable
type Stack[T any] struct{ items []T }
var s Stack // cannot use generic type Stack[T any] without instantiation
func Zero[T any]() T { var z T; return z }
var _ = Zero() // in call to Zero, cannot infer T (declared at ...)
type Number interface{ int | float64 }
type MyInt int
var _ = Sum([]MyInt{1, 2}) // MyInt does not satisfy Number (possibly missing ~ for int in Number)Each line's comment is the exact message observed (positions trimmed).
Experiment 2: see the GC shapes
package shape
//go:noinline
func Id[T any](x T) T { return x }
type A struct{ n int }
func Use() { _ = Id(1); _ = Id("s"); _ = Id(&A{}); _ = Id(new(int)) }go build -gcflags=-S ./shape 2>&1 | grep -E 'STEXT|SRODATA' | grep -E 'Id\[|dict' | grep -v '\]\.arg' | awk '{print $1, $2}' | sortOutput (verified, sorted):
scratch/shape..dict.Id[*int] SRODATA
scratch/shape..dict.Id[*scratch/shape.A] SRODATA
scratch/shape..dict.Id[int] SRODATA
scratch/shape..dict.Id[string] SRODATA
scratch/shape.Id[*int] STEXT
scratch/shape.Id[*scratch/shape.A] STEXT
scratch/shape.Id[go.shape.*uint8] STEXT
scratch/shape.Id[go.shape.int] STEXT
scratch/shape.Id[go.shape.string] STEXT
scratch/shape.Id[int] STEXT
scratch/shape.Id[string] STEXTFour dictionaries (one per concrete type argument) and three shape bodies: Id[go.shape.*uint8] is the single body for both *A and *int. The four concrete-named Id[...] symbols are wrappers (marked WRAPPER in the full listing) that call the shape body with their dictionary; they exist for function values and reflection.
Experiment 3: generic versus interface speed
cd docs/snippets/go/generics/go
go test -run '^$' -bench . -benchmem ./benchOutput (verified, one run, 1024 elements):
BenchmarkSumConcrete-12 4293868 259.2 ns/op 0 B/op 0 allocs/op
BenchmarkSumGeneric-12 4809210 250.7 ns/op 0 B/op 0 allocs/op
BenchmarkSumAny-12 3865874 317.1 ns/op 0 B/op 0 allocs/op
BenchmarkTotalIface-12 1440805 832.6 ns/op 0 B/op 0 allocs/op
BenchmarkTotalGeneric-12 1536858 785.5 ns/op 0 B/op 0 allocs/opRead it as: a generic loop over int matches hand-written code; boxing into []any costs about a quarter more; a method call through a pointer-shaped type parameter is in the same range as an interface call. Run with -count 10 and benchstat before drawing conclusions on your hardware.
Experiment 4: generic methods and the language version
Remove the //go:build go1.27 line from genericmethod/genericmethod.go (in a copy) and build:
generic method requires go1.27 or later (-lang was set to go1.24; check go.mod)Restore the line: the file compiles, and go test ./genericmethod prints ok. Then add var _ Mapper = L{} with a generic Map and observe L does not implement Mapper (wrong type for method Map) with the have/want lines (verified).
Experiment 5: vet and the runtime comparable panic
func Print[T ~int | ~string](t T) { fmt.Printf("%d\n", t) }go vet prints fmt.Printf format %d has arg t of wrong type T (contains ~string) (verified). Then run a main that calls Index(xs, v) with xs holding one []int value and v another []int boxed in any: output panic: runtime error: comparing uncomparable type []int followed by goroutine 1 [running]: and main.Index[...](...) (verified).
Experiment 6: a generic cache under load (expected, not run)
Wrap lru.Cache[string, []byte] in an HTTP handler and drive it with wrk -t4 -c64 -d30s http://127.0.0.1:8080/item?id=... against a backing PostgreSQL. Expected: a high hit ratio cuts p99 latency to the in-memory path; go test -race stays clean; pg_stat_statements shows the item query rate dropping by the hit ratio. This is expected output; it was not run.
Common misconceptions
| Belief | Reality |
|---|---|
| "Generics are faster than interfaces" | Often equal; method calls on pointer shapes go through a dictionary |
| "Go monomorphises like C++" | gc shares one body per GC shape and passes dictionaries |
"T any means the function takes values of any type at run time" | Each instantiation fixes one type at compile time |
"int or float64 union accepts my type Cents int" | Only with ~int |
"comparable means == never panics" | Interfaces satisfy it since Go 1.20 and can panic |
| "Constraints are a special syntax" | They are interfaces; type-set interfaces are constraint-only |
| "Inference uses the result type" | Not for calls; only assignment of uncalled generic functions |
| "Go has no generic methods" | Go 1.27 added them; interface methods still cannot be generic |
| "A generic method can implement an interface" | Never |
"maps.Keys returns a slice" | It returns iter.Seq[K] since Go 1.23 |
"Use x/exp/constraints for Ordered" | Use cmp.Ordered (Go 1.21) |
| "Generic aliases create new types" | They are identical to the aliased type |
"I can read x.Field if all types have it" | No field constraints |
"Wrap everything in Option[T]" | Go convention is (T, bool) and (T, error) |
| "More type parameters means more reuse" | Usually means over-abstraction |
Cheat sheet
| Topic | What to remember |
|---|---|
| Syntax | func F[T C](x T), type G[T C] struct, func (g G[T]) M() |
| Constraint | An interface; any, comparable, cmp.Ordered, unions, ~T |
~T | Underlying type T; needed for named types |
comparable | == allowed; any satisfies it since 1.20; may panic |
| Inference | From arguments, constants, constraints; not from call results |
| Explicit | F[int](x); prefix allowed; F[int] is a value |
| Zero value | var zero T or *new(T); return (T, bool) |
| Containers | Stack, Set, LRU; pass comparison functions |
| Stdlib | slices, maps, cmp, iter, sync.OnceValue(s), atomic.Pointer, errors.AsType |
| Iterators | iter.Seq[T]; check yield; defer stop() after iter.Pull |
| Return input type | [S ~[]E, E any], [M ~map[K]V, ...] |
| Versions | 1.18 generics; 1.21 stdlib; 1.23 iter; 1.24 aliases; 1.26 self-ref; 1.27 methods |
| Implementation | GC shape stenciling plus dictionaries; all pointers share a shape |
| Limits | No specialization, no HKT, no field constraints, no generic interface methods |
| Rule | Write code first; generalise on the second identical copy |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — Why does Sum([]Cents{1, 2}) fail with Number interface{ int64 | float64 } but work with ~int64 | ~float64? Important
Answer
Answer: Cents is a defined type whose underlying type is int64. A plain term int64 admits only int64 itself; ~int64 admits every type whose underlying type is int64. The compiler says so: possibly missing ~ for int64 in Number. See Type sets.
2 — Does Index([]any{1, "x"}, any("x")) compile? Can Index on []any ever panic? Important
Answer
Answer: It compiles since Go 1.20, because interface types satisfy comparable (they are comparable but not strictly comparable). It panics at run time if two compared values have the same non-comparable dynamic type, for example two []int: comparing uncomparable type []int. See comparable.
3 — Why does x := Zero() fail while Zero[int]() works? Must-know
Answer
Answer: T appears only in the result. Inference uses arguments, constants and constraints, not the variable the call is assigned to, so the compiler reports cannot infer T. Supplying the type argument explicitly fixes it. See Type inference.
4 — You need a function that creates []T values and calls a pointer-receiver Set method on each. What is the signature? Good to know
Answer
Answer: func ParseAll[T any, PT interface{ *T; Set(string) error }](in []string) ([]T, error), called as ParseAll[Port](in). PT is inferred from its constraint, and PT(&out[i]).Set(s) calls the method. See Methods in constraints.
5 — Why does slices.Clone have two type parameters? Good to know
Answer
Answer: [S ~[]E, E any] returns S, so a named slice type such as Emails comes back with its methods. A single [E any] version would return []E. See Deconstructing type parameters.
6 — Your team proposes changing func Copy(dst io.Writer, src io.Reader) to func Copy[W io.Writer, R io.Reader](dst W, src R) for speed. What do you answer? Important
Answer
Answer: Do not. The function only calls methods, so an interface is the right tool; with GC shape stenciling the generic version is usually no faster (pointer-shaped arguments share one body and call methods through the dictionary), and it is harder to read. See When to use generics and GC shape stenciling.
7 — In Go 1.27, can func (l L) Map[F any](f func(int) F) []F make L implement interface{ Map(func(int) int) []int }? Good to know
Answer
Answer: No. Generic methods cannot implement interface methods, and interface methods cannot declare type parameters. The compiler reports wrong type for method Map with the have and want signatures. See Generic methods.
8 — Which compiled bodies does gc produce for Id(1), Id(&A{}) and Id(new(int))? Good to know
Answer
Answer: Two shape instantiations: Id[go.shape.int] and one Id[go.shape.*uint8] shared by both pointer types, plus one dictionary per concrete type argument (..dict.Id[int], ..dict.Id[*A], ..dict.Id[*int]) and thin wrappers. See the Lab.
9 — What must you do after next, stop := iter.Pull(seq) if you might not read to the end? Good to know
Answer
Answer: Call stop, typically defer stop() immediately. Otherwise the coroutine running seq is not released. Also never call next or stop from several goroutines at once. See Iterators.
10 — Why prefer atomic.Pointer[Config] over atomic.Value for configuration snapshots? Important
Answer
Answer: It is typed: Load returns *Config without an assertion, Store rejects other types at compile time, and CompareAndSwap takes *Config values. Treat the pointed-to snapshot as immutable and swap whole snapshots. See The generic standard library.
Glossary
| Term | Meaning |
|---|---|
| Generics | Writing functions and types parameterised by types; in Go since 1.18 |
| Type parameter | A named placeholder for a type, declared in [...] |
| Type argument | The concrete type substituted for a type parameter |
| Type parameter list | [T any, K comparable] after a function, type or (1.27) method name |
| Generic function | A function with a type parameter list |
| Generic type | A defined type with a type parameter list, such as Stack[T] |
| Generic method | A method with its own type parameters (Go 1.27) |
| Generic interface | An interface type with type parameters, such as Getter[T] |
| Generic type alias | type A[P C] = T, supported since Go 1.24 |
| Constraint | The interface that limits a type parameter's type arguments |
| Type set | The set of types an interface permits |
| Union | Type terms joined with a vertical bar in an interface |
~T (tilde term) | All types whose underlying type is T |
| Underlying type | The type a defined type is built on (int for type Celsius int) |
| General interface | An interface with type terms or comparable; constraint-only |
any | Alias for interface{}; the loosest constraint |
comparable | Predeclared constraint permitting == and != |
| Strictly comparable | Comparable and guaranteed not to panic on == |
cmp.Ordered | Standard constraint for types supporting < |
constraints package | golang.org/x/exp/constraints: Go 1.18 stop-gap with Ordered, Integer, Float |
| Satisfy | A type argument satisfies a constraint if it is in its type set |
| Instantiation | Substituting type arguments and checking constraints |
| Explicit instantiation | Writing type arguments, F[int] |
| Partial instantiation | Giving a prefix of type arguments, inferring the rest |
| Type inference | Deducing type arguments from arguments, constants, constraints and context |
| Constraint type inference | Inferring a type parameter from another's constraint (PT interface{ *T }) |
| Core type | Former spec concept for a constraint's single underlying type; replaced by prose in Go 1.25 |
| Pointer-method pattern | PT interface{ *T; M() } to call pointer methods on T |
| Self-referential constraint | type Adder[A Adder[A]] interface{...}, Go 1.26 |
| Zero value of T | var zero T or *new(T) |
| Stenciling | Generating a copy of a generic body for type arguments |
| GC shape | Group of types sharing one compiled body (same underlying type, or any pointer) |
| Shape instantiation | Compiled body for one GC shape, named F[go.shape.int] |
| Dictionary | Hidden static argument with type information for a shape body |
| Monomorphisation | One compiled copy per type argument (C++, Rust); not what gc does |
| Specialization | A custom body for specific type arguments; not supported |
| Higher-kinded type | A type parameter that is itself generic; not supported |
iter.Seq | func(yield func(V) bool): a push iterator |
iter.Pull | Converts a push iterator into next and stop functions |
sync.OnceValue | Wraps a function so it runs once and returns its cached result |
atomic.Pointer | Typed atomic pointer with Load, Store, Swap, CompareAndSwap |
errors.AsType | Generic errors.As returning (E, bool), Go 1.26 |
| Over-abstraction | Generic code where a concrete type or interface would be simpler |
| gopls | Go language server; hover and inlay hints for type arguments |
@template (PHPStan) | Docblock tag declaring a type variable checked by static analysis |
| PHPStan generics | Static-analysis-only generics for PHP via docblocks |
References
Read for Go 1.24 to 1.27 behaviour; pages were fetched and saved on 2026-11-26. pkg.go.dev returned HTTP 403 to automated fetches, so package APIs were read from the Go source on go.dev/src and with go doc from the installed Go 1.27.4.
- The Go Programming Language Specification (language version go1.27, May 26, 2026): type parameter declarations, type constraints, type sets, satisfying a constraint, instantiations, type inference, generic methods, alias declarations.
- Type Parameters Proposal: the accepted design.
- Go 1.18 Implementation of Generics via Dictionaries and Gcshape Stenciling: GC shapes and dictionaries.
- When To Use Generics (Ian Lance Taylor, 2022): the guidelines and the opening quote.
- An Introduction To Generics: type parameters, type sets, inference.
- Tutorial: Getting started with generics.
- Deconstructing Type Parameters:
S ~[]E. - All your comparable types: the Go 1.20
comparablechange. - Everything You Always Wanted to Know About Type Inference.
- What's in an (Alias) Name?: generic aliases.
- Range Over Function Types: iterators.
- Go FAQ: generics rationale, implementation, comparison with Java/C++/Rust, square brackets, the (superseded) generic methods entry.
- Effective Go: note that it does not cover generics.
- The Go Memory Model: atomic operations used by
atomic.Pointer. - Release notes: Go 1.18, Go 1.19, Go 1.20, Go 1.21, Go 1.22, Go 1.23, Go 1.24, Go 1.25, Go 1.26, Go 1.27.
- Go Code Review Comments: receiver naming, which applies unchanged to generic types.
- Package source (Go 1.27): cmp, iter, slices, maps iterators, sync OnceFunc/OnceValue, sync/atomic types.
- golang.org/x/exp/constraints source.
- gopls inlay hints and gopls features.
- PHPStan: Generics in PHP using PHPDocs and PHPStan PHPDoc types.