Generics: Type Parameters, Constraints and Generic Types
Learn Go generics: type parameters, constraints such as cmp.Ordered, generic Map, Filter and Reduce functions, a generic Stack type, and the compiler error for an unsupported type.
In this lesson you will
- Write generic functions
- Use constraints
- Write a generic type
- Read the constraint error
About 28 minutes
One Max for every type
Mei needs the largest weight of a list of float64 values, the latest delivery of a list of times, and the alphabetically last region name. Before Go 1.18 that meant writing three nearly identical functions or using the empty interface and giving up type safety. Generics let you write the function once, with a type parameter in square brackets, and the compiler generates or checks it for each type that you use.
A generic function is declared like func Max[T cmp.Ordered](a, b T) T. The part in brackets lists the type parameters and their constraints. A constraint is an interface that says what T must support: any means no restriction, comparable allows == and !=, and cmp.Ordered, from the cmp package, allows the comparison operators , which covers numbers and strings. The compiler usually infers T from the arguments, so you rarely write it out. Types can be generic as well: type Stack[T any] struct { items []T }, and its methods use T. Generics are best for data structures and for functions that operate on slices and maps without caring about the element type, such as Map, Filter and Reduce, and the standard library has several of them in the slices and maps packages. For behaviour that differs by type, interfaces are still the right tool.
| Part | Example |
|---|---|
| Type parameter | func Max[T cmp.Ordered](a, b T) T |
| Constraint any | Any type, no operations |
| Constraint comparable | Allows == and != |
| Constraint cmp.Ordered | Allows on numbers and strings |
| Generic type | type Stack[T any] struct { items []T } |
package main
import (
"cmp"
"fmt"
"strings"
)
func Max[T cmp.Ordered](a, b T) T {
if a > b {
return a
}
return b
}
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
}
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
}
func Reduce[T, A any](xs []T, start A, f func(A, T) A) A {
acc := start
for _, x := range xs {
acc = f(acc, x)
}
return acc
}
type Stack[T any] struct{ items []T }
func (s *Stack[T]) Push(x T) { s.items = append(s.items, x) }
func (s *Stack[T]) Pop() (T, bool) {
var zero T
if len(s.items) == 0 {
return zero, false
}
x := s.items[len(s.items)-1]
s.items = s.items[:len(s.items)-1]
return x, true
}
func main() {
fmt.Println("Max ints:", Max(3, 9), "| floats:", Max(2.5, 0.4), "| strings:", Max("north", "south"))
w := []float64{0.4, 2.5, 12.0, 7.25, 0.9}
heavy := Filter(w, func(x float64) bool { return x >= 2.5 })
labels := Map(heavy, func(x float64) string { return fmt.Sprintf("%.1fkg", x) })
total := Reduce(w, 0.0, func(a, x float64) float64 { return a + x })
fmt.Println("heavy:", strings.Join(labels, ","), "| total:", total)
lengths := Map([]string{"north", "south", "east"}, func(s string) int { return len(s) })
fmt.Println("lengths:", lengths, "| longest:", Reduce(lengths, 0, Max[int]))
var si Stack[int]
si.Push(1); si.Push(2); si.Push(3)
a, _ := si.Pop()
b, _ := si.Pop()
var ss Stack[string]
ss.Push("only")
s1, ok1 := ss.Pop()
s2, ok2 := ss.Pop()
fmt.Println("int stack popped:", a, b, "| string stack:", s1, ok1, "then", fmt.Sprintf("%q", s2), ok2)
}
Max ints: 9 | floats: 2.5 | strings: south
heavy: 2.5kg,12.0kg,7.2kg | total: 23.049999999999997
lengths: [5 5 4] | longest: 5
int stack popped: 3 2 | string stack: only true then "" false
package main
import (
"cmp"
"fmt"
)
func Max[T cmp.Ordered](a, b T) T {
if a > b {
return a
}
return b
}
func main() {
type Parcel struct{ Kg float64 }
fmt.Println(Max(Parcel{1}, Parcel{2}))
}
# demo
./main.go:17:17: Parcel does not satisfy cmp.Ordered (Parcel missing in ~int | ~int8 | ~int16 | ~int32 | ~int64 | ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr | ~float32 | ~float64 | ~string)
./main.go:17:17: Parcel does not satisfy cmp.Ordered (Parcel missing in ~int | ~int8 | ~int16 | ~int32 | ~int64 | ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr | ~float32 | ~float64 | ~string)
One Max worked for ints, floats and strings: 9, 2.5 and “south”, and the compiler inferred T from the arguments each time. Filter, Map and Reduce combine into a small pipeline: the weights of at least 2.5 kilograms became the labels 2.5kg,12.0kg,7.2kg, and Reduce added all five weights, giving 23.049999999999997, which is 23.05 on paper, and the tail of digits is ordinary floating point rounding from adding in that order, the same value that Python gets. Note that the label of 7.25 shows as 7.2 because %.1f rounds the exact binary value of the float, and that Reduce with Max[int] found the longest of the three region names, 5 letters. The generic Stack held ints and strings, and Pop returned the zero value and false for an empty stack, which is the usual Go replacement for an exception: the int stack popped 3 and 2, and the string stack popped “only” and then reported empty.
The second program tried to use Max with a struct, which has no ordering, and the compiler refused it at compile time with the message shown, which names the constraint that the type fails to meet. A mistake like this appears at the line where you call the function, and not inside the generic code, which is the benefit of constraints: they document and enforce what a type parameter may do.
Check by hand: the weights [0.4, 2.5, 12.0, 7.25, 0.9] add up to 23.05. Those at least 2.5 are 2.5, 12.0 and 7.25. The region names north, south and east have 5, 5 and 4 letters, so the longest is 5. A stack is last in, first out, so after pushing 1, 2 and 3, the first two pops give 3 and 2.
If a function works on an interface, use the interface. Generics shine for containers and for helpers over slices and maps. Code that is clearer without them should stay without them.
Write Max(3, 9) and not Max[int](3, 9). Spell out the type parameter only when the compiler cannot infer it, as with Reduce(lengths, 0, Max[int]) where the function value needs its type.
Every program in this lesson was built and run with Go 1.24 while the course was written. Go releases twice a year, so check go.dev for the current version and release notes. Generics need Go 1.18 or later, and the cmp package needs Go 1.21.
Practice
Write a generic function Keys that returns the keys of a map, and sort the result. Write a generic Set[T comparable] with Add and Has. Try to use a generic function with a type that fails its constraint and read the message.
Check what you learned
Five quick questions. Pick an answer and you will see straight away whether it is right and why.
What does cmp.Ordered allow?
- Only integers
- Any type
- Only comparison with ==
- The operators on numbers and strings
It is a constraint.
What does the compiler do with Max(3, 9)?
- Asks you for T
- Uses any
- Infers T as int
- Fails
Type inference.
What does Pop return for an empty stack?
- A panic
- nil always
- The zero value and false
- An exception
Idiomatic Go.
Why was Max(Parcel, Parcel) rejected?
- Structs cannot be passed
- Parcel does not satisfy cmp.Ordered
- The function is private
- It is a runtime error
A compile-time check.
When should you prefer an interface to generics?
- Never
- When behaviour differs by type
- For all containers
- For numbers
Generics are for same code, many types.
Summary
- Type parameters let one function or type work for many types.
- Constraints state what a type must support; cmp.Ordered allows ordering.
- Map, Filter and Reduce are natural generic helpers.
- The compiler checks constraints at compile time.
Questions
Do generics make programs slower?
No. Go implements them efficiently, and the cost is usually negligible. Measure if it matters.
Can methods have their own type parameters?
No. Methods can use the type parameters of their receiver type but cannot declare new ones. Use a generic function instead.
What is the slices package?
A standard package of generic helpers such as slices.Sort, slices.Contains and slices.Index. Use it before writing your own.
