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.

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. anyis an alias forinterface{};comparableis a predeclared constraint requiring==support, and it is what makesmap[K]Vkeys andswitch v := x.(type)viable.- Without
~, a named type with anintunderlying type does not satisfyint, sotype Celsius float64fails afloat64constraint. Use~float64. - Type inference covers arguments but not results:
f(x)infers fromx, whilevar g = fcannot infer anything and needsf[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
// 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
| Constraint | Accepts | Rejects | Use |
|---|---|---|---|
any | every type | nothing | containers, transformations |
comparable | types supporting == | slices, maps, funcs | map keys, dedupe, slices.Contains |
~int | int and type MyInt int | int64, float64 | integer-only algorithms |
~float64 | float64 and named float64 types | float32 | numeric helpers on a specific width |
Integer | Float (union) | members of the union | named types without ~ | generic arithmetic |
fmt.Stringer | types with String() string | int, any | formatting helpers |
cmp.Ordered | ordered built-in types | structs, slices | slices.Sort, comparisons |
interface{ ~int; String() string } | types with both | one or the other | generating 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
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 comparableThe 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
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 TGo 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
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
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 firstEach 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
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 symptom | Cause | Fix |
|---|---|---|
X does not satisfy comparable (struct containing []string cannot be compared) | a non-comparable type used where comparable is required | use a comparable key, or hash the fields |
cannot use type X as type T in argument on a named type | the constraint listed int instead of ~int | add ~ to accept named types with that underlying type |
cannot infer T | no argument carries T | instantiate explicitly: f[int](...) |
invalid operation: operator - not defined on a | the operation is not supported by every union member | narrow the constraint or compute differently |
type parameter cannot be used as an interface value confusion in any assertions | a type parameter's method set is its constraint's | use the constraint's methods, or convert to any deliberately |
missing function body in a generic declaration | a body-less declaration outside assembly files | provide a body or use assembly-compatible declarations |
methods cannot have type parameters | method 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 name | the parameter name collides with a package | rename 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 toolsSmall utilities that fit Go work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Go guides
All Go guidesGo iota: Enumerations, Bitmask Flags, and Constant Expressions
How iota advances per const line, typed enums with gaps, bit flags with 1 << iota, and the unit scale pattern that shifts with one blank line.
Go JSON: Marshaling, Unmarshaling, Struct Tags, and Custom Parsers
Struct tags, omitempty that skips false and zero, custom marshalers without recursion, RawMessage for tagged unions, and float64 precision loss.
Go Strings, Runes, and Bytes: UTF-8 Encoding, Conversion, and Memory
Bytes versus runes, len that counts bytes, slicing that splits characters, Builder for linear concatenation, and normalization the standard library omits.
Go select Statement: Non-Blocking Operations, Timeouts, and Nil Channels
Random choice among ready cases, non-blocking polls with default, nil channels that disable a case, timer reuse, and labeled breaks out of a loop.
More in Go
All Go guidesThe guides filed next to this one in Go, in library order.