Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Go Generics: Type Parameters, Constraints, any, and comparable

Type parameter syntax, what the tilde in a constraint union actually admits, where inference stops, and why a struct containing a slice cannot satisfy comparable.

~4 min readGo
#Go#Generics#Data Structures
3D illustration of generic container brackets accepting diverse data types constrained by comparable union rules

Go has had generics since 1.18: a function or type can declare type parameters, and a constraint interface restricts which types may fill them. The two constraints that appear everywhere are any — the empty interface, meaning no restriction — and comparable, meaning the type supports == and !=. Between them and a few small unions lies most of what practical generic Go needs, and the language deliberately stops there: there is no operator overloading, no specialization, and no type-level arithmetic.

Quick Summary

  • A type parameter list goes after the function name and before the parameters: func Map[T, U any](in []T, f func(T) U) []U.
  • Constraints are interfaces, optionally with a type union: interface{ ~int | ~int64 }. The tilde admits any type whose underlying type is the one listed.
  • any is an alias for interface{}; comparable is a predeclared constraint requiring == support, and it is what makes map[K]V keys and switch v := x.(type) viable.
  • Without ~, a named type with an int underlying type does not satisfy int, so type Celsius float64 fails a float64 constraint. Use ~float64.
  • Type inference covers arguments but not results: f(x) infers from x, while var g = f cannot infer anything and needs f[int].
  • A constraint may embed a comparable-satisfying interface or a union, but not both methods and a union in a way that requires a runtime dispatch — the compiler forbids using a generic value as an interface method receiver combination it cannot resolve.
  • Methods cannot declare type parameters. Only functions and types can, which is why generic algorithms arrive as functions, not as methods.

Basic syntax and type signatures

go
// Function with two type parameters. func Map[T, U any](in []T, f func(T) U) []U { out := make([]U, 0, len(in)) for _, v := range in { out = append(out, f(v)) } return out } // Constraint with a type union and an approximation element. type Number interface { ~int | ~int8 | ~int16 | ~int32 | ~int64 | ~float32 | ~float64 } func Sum[T Number](xs []T) T { var total T for _, x := range xs { total += x } return total } // Constraint with methods works when every member has them. type Stringer interface { String() string } func Join[T fmt.Stringer](xs []T, sep string) string { parts := make([]string, len(xs)) for i, x := range xs { parts[i] = x.String() } return strings.Join(parts, sep) } // Generic type: a type parameter on the type itself. type Stack[T any] struct { items []T } func (s *Stack[T]) Push(v T) { s.items = append(s.items, v) } func (s *Stack[T]) Pop() (T, bool) { var zero T if len(s.items) == 0 { return zero, false } v := s.items[len(s.items)-1] s.items = s.items[:len(s.items)-1] return v, true }

var zero T is the idiom for a type parameter's zero value. nil does not work because T may be a non-nilable type such as int, and the compiler rejects return nil for that reason.

Comparison of constraints

ConstraintAcceptsRejectsUse
anyevery typenothingcontainers, transformations
comparabletypes supporting ==slices, maps, funcsmap keys, dedupe, slices.Contains
~intint and type MyInt intint64, float64integer-only algorithms
~float64float64 and named float64 typesfloat32numeric helpers on a specific width
Integer | Float (union)members of the unionnamed types without ~generic arithmetic
fmt.Stringertypes with String() stringint, anyformatting helpers
cmp.Orderedordered built-in typesstructs, slicesslices.Sort, comparisons
interface{ ~int; String() string }types with bothone or the othergenerating string forms of numbers

cmp.Ordered (Go 1.21, cmp package) is ~int | ~int8 | ... | ~string, which is why slices.Sort works on any ordered element type without a user-written constraint.

Practical edge cases and deep dives

1. comparable is not == on structs that contain slices

go
type Pair[K comparable, V any] struct { Key K Val V } func Index[K comparable, V any](items []Pair[K, V]) map[K]V { m := make(map[K]V, len(items)) for _, p := range items { m[p.Key] = p.Val } return m } // A struct containing a slice is not comparable, even though it looks like a key. type Record struct { ID string Tags []string } // Index([]Pair[Record, int]{}) // error: Record does not satisfy comparable

The error message is Record does not satisfy comparable (struct containing []string cannot be compared). The compiler checks comparability at instantiation, not at declaration, so a generic function constrained by comparable compiles fine and fails only where a bad type is passed. The fix is a key type that is actually comparable — an ID, a hash, or a string joined from the fields — rather than a reflect.DeepEqual call inside the loop.

2. Type inference gaps and the explicit instantiation

go
func Zero[T any]() T { var zero T return zero } // var z = Zero() // error: cannot infer T var z = Zero[int]() // ok // Inference works from arguments. func Min[T cmp.Ordered](a, b T) T { if a < b { return a } return b } m := Min(3, 7) // T = int // It does not flow from the result type into the parameter in general. func Make[T any](n int) []T { return make([]T, n) } // xs := Make(3) // error: cannot infer T xs := Make[string](3) // ok // Inference fails when the argument type is untyped nil or a bare interface value. // Min(nil, nil) // error: cannot infer T

Go infers type arguments from function arguments, and in some cases from the assignment context (since 1.21 the compiler handles more cases, but it never guesses from an empty argument list). The practical consequence is that constructors and factories take an argument of the type parameter's type — New[T](v T) — or expect an explicit instantiation.

3. Union constraints and the operation that only some members support

go
type Signed interface{ ~int | ~int64 } type Unsigned interface{ ~uint | ~uint64 } func MaxUnsigned[T Unsigned](xs []T) T { var max T for _, x := range xs { if x > max { max = x } } return max } // An operation not supported by every member is a compile error at the // definition site, not at the call site. func Bad[T Signed | string](a T) T { // return a + a // error: invalid operation: operator + not defined on a return a }

The union constraint's method set is the intersection of its members' method sets, plus the operations the compiler can prove are common to all members. Since all of ~int and ~string support +, that one compiles; - does not, because strings have no subtraction. Errors surface when the generic function is defined, which is the useful place: the constraint, not the instantiation, is wrong.

4. Generic types with methods, and the interface boundary

go
type Set[T comparable] map[T]struct{} func NewSet[T comparable](items ...T) Set[T] { s := make(Set[T], len(items)) for _, item := range items { s[item] = struct{}{} } return s } func (s Set[T]) Add(v T) { s[v] = struct{}{} } func (s Set[T]) Has(v T) bool { _, ok := s[v]; return ok } func (s Set[T]) Len() int { return len(s) } // A generic type cannot be used as an interface method set directly, // but a concrete instantiation can satisfy an interface. type Lenner interface{ Len() int } var _ Lenner = NewSet(1, 2, 3) // Set[int] has Len() int // var _ Lenner = Set[string]{} // also fine; instantiation happens first

Each instantiation is a distinct type: Set[int] and Set[string] are unrelated to each other and to the generic Set[T] in the type parameter position. That is why an interface cannot be satisfied by "any Set[T]" and why generic code that must cross an interface boundary passes concrete instantiations.

5. Generic function values, closures, and the missing method type parameters

go
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 } // A generic function cannot be a method value with its own parameters, // but it can be stored as a value after instantiation. f := Filter[int] odds := f([]int{1, 2, 3, 4}, func(n int) bool { return n%2 == 1 }) // Methods cannot declare type parameters; use a generic function instead. type Repo struct{ db *sql.DB } func Query[T any](r *Repo, q string) ([]T, error) { /* ... */ return nil, nil }

Filter[int] is an instantiated function value whose type is func([]int, func(int) bool) []int. The reason methods cannot take type parameters is that method sets must be resolvable without instantiation — a method with its own parameters on a generic type would have two independent instantiation axes. The workaround is what every Go codebase settles on: a generic function that takes the receiver as its first argument.

Common mistakes and compiler errors

Error or symptomCauseFix
X does not satisfy comparable (struct containing []string cannot be compared)a non-comparable type used where comparable is requireduse a comparable key, or hash the fields
cannot use type X as type T in argument on a named typethe constraint listed int instead of ~intadd ~ to accept named types with that underlying type
cannot infer Tno argument carries Tinstantiate explicitly: f[int](...)
invalid operation: operator - not defined on athe operation is not supported by every union membernarrow the constraint or compute differently
type parameter cannot be used as an interface value confusion in any assertionsa type parameter's method set is its constraint'suse the constraint's methods, or convert to any deliberately
missing function body in a generic declarationa body-less declaration outside assembly filesprovide a body or use assembly-compatible declarations
methods cannot have type parametersmethod declared as func (t T) M[U any]()move the parameter to the function or the type
T is not a type when T shadows a package namethe parameter name collides with a packagerename the parameter

The one that costs the most time is the missing ~: a codebase defines type UserID int64, passes it to Sum[T Number] where Number lists int64, and gets a constraint failure that reads like a type error but is a constraint error. Writing constraints with ~ from the start costs nothing and saves the diagnosis later.

Try matching browser tools

All tools

Small utilities that fit Go work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Go guides

More in Go

All Go guides

The guides filed next to this one in Go, in library order.