Generics
Before Go 1.18, a function that found the maximum of a slice had to be written once for []int, again for []float64, and again for []string, or use any and lose type safety. Generics (type parameters) let you write it once, for every type that supports what the function needs, with full compile-time checking.
A generic function
package main
import "fmt"
// T is a type parameter. The constraint says which types are allowed.
func Max[T int | float64 | string](values []T) T {
best := values[0]
for _, v := range values[1:] {
if v > best {
best = v
}
}
return best
}
func main() {
fmt.Println(Max([]int{3, 9, 4}))
fmt.Println(Max([]float64{2.5, -1, 8.25}))
fmt.Println(Max([]string{"pear", "apple", "zebra"}))
fmt.Println(Max[int]([]int{7})) // you can also state T explicitly
}9 8.25 zebra 7
[T int | float64 | string]declares a type parameterTand its constraint: the set of typesTmay be.- Go infers
Tfrom the arguments, so you usually don't writeMax[int]. - Inside the function you can only use operations every allowed type supports. Here,
>works for all three.
Calling it with a type that isn't allowed is a compile error:
package main
import "fmt"
func Max[T int | float64 | string](values []T) T { return values[0] }
func main() {
fmt.Println(Max([]bool{true, false}))
}# command-line-arguments ./main.go:8:17: bool does not satisfy int | float64 | string (bool missing in int | float64 | string)
Constraints
A constraint is an interface. Besides methods, constraint interfaces can list types. The standard cmp.Ordered covers every type that supports < and >:
package main
import (
"cmp"
"fmt"
)
type Number interface {
~int | ~int32 | ~int64 | ~float32 | ~float64
}
func Sum[T Number](nums []T) T {
var total T // the zero value of T
for _, n := range nums {
total += n
}
return total
}
func Clamp[T cmp.Ordered](v, lo, hi T) T {
return min(max(v, lo), hi)
}
type Cents int64 // a named type based on int64
func main() {
fmt.Println(Sum([]int{1, 2, 3}), Sum([]float64{0.5, 0.25}))
fmt.Println(Sum([]Cents{1999, 4950})) // ~int64 allows Cents too
fmt.Println(Clamp(150, 0, 100), Clamp("m", "a", "k"))
}6 0.75 6949 100 k
| Constraint | Allows |
|---|---|
any |
Every type (you can only assign, compare to nothing, pass around) |
comparable |
Types that support == and !=: needed for map keys |
cmp.Ordered |
Integers, floats and strings: types that support < |
~int64 |
int64 and any type defined on it, like type Cents int64 |
interface{ String() string } |
Types with that method |
Generic types
Types can have type parameters too. Here's a type-safe stack that works for any element type:
package main
import "fmt"
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
}
func (s *Stack[T]) Len() int { return len(s.items) }
func main() {
var nums Stack[int]
nums.Push(1)
nums.Push(2)
v, _ := nums.Pop()
fmt.Println(v, nums.Len())
words := Stack[string]{}
words.Push("hello")
w, ok := words.Pop()
_, ok2 := words.Pop()
fmt.Println(w, ok, ok2)
}2 1 hello true false
Stack[int] and Stack[string] are separate types, and nums.Push("x") won't compile. With an []any stack, you'd need type assertions on every Pop and mistakes would only show up at run time.
Useful generic helpers
Map, filter and reduce are the classic examples:
package main
import (
"fmt"
"strings"
)
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
}
func Filter[T any](in []T, keep func(T) bool) []T {
var out []T
for _, v := range in {
if keep(v) {
out = append(out, v)
}
}
return out
}
func GroupBy[T any, K comparable](in []T, key func(T) K) map[K][]T {
groups := make(map[K][]T)
for _, v := range in {
k := key(v)
groups[k] = append(groups[k], v)
}
return groups
}
type Order struct {
ID int
Region string
Total float64
}
func main() {
names := []string{"asha", "ravi", "lee"}
fmt.Println(Map(names, strings.ToUpper))
fmt.Println(Map(names, func(s string) int { return len(s) }))
orders := []Order{{1, "north", 120}, {2, "south", 45}, {3, "north", 300}, {4, "east", 80}}
big := Filter(orders, func(o Order) bool { return o.Total >= 100 })
fmt.Println(big)
byRegion := GroupBy(orders, func(o Order) string { return o.Region })
fmt.Println(len(byRegion["north"]), len(byRegion["south"]), len(byRegion["east"]))
}[ASHA RAVI LEE]
[4 4 3]
[{1 north 120} {3 north 300}]
2 1 1Map has two type parameters: the input element type T and the output type U. GroupBy needs its key type to be comparable because it's used as a map key.
The standard library already has many
Before writing your own, check slices, maps and cmp, which are all generic:
package main
import (
"cmp"
"fmt"
"maps"
"slices"
)
type User struct {
Name string
Age int
}
func main() {
users := []User{{"Ravi", 28}, {"Asha", 31}, {"Lee", 28}}
slices.SortFunc(users, func(a, b User) int {
return cmp.Or(cmp.Compare(a.Age, b.Age), cmp.Compare(a.Name, b.Name))
})
fmt.Println(users)
i := slices.IndexFunc(users, func(u User) bool { return u.Name == "Asha" })
fmt.Println("Asha is at index", i)
stock := map[string]int{"pen": 10, "ink": 0, "pad": 4}
fmt.Println(slices.Sorted(maps.Keys(stock)))
maps.DeleteFunc(stock, func(k string, v int) bool { return v == 0 })
fmt.Println(stock)
}[{Lee 28} {Ravi 28} {Asha 31}]
Asha is at index 2
[ink pad pen]
map[pad:4 pen:10]cmp.Or returns its first non-zero argument, a neat way to sort by several fields: by age, then by name.
Iterators
Since Go 1.23, a function with the right shape can be looped over with range. maps.Keys and slices.Values return these iterators, and you can write your own generic ones:
package main
import (
"fmt"
"iter"
)
// Fib yields Fibonacci numbers until the loop stops asking.
func Fib() iter.Seq[int] {
return func(yield func(int) bool) {
a, b := 0, 1
for {
if !yield(a) {
return
}
a, b = b, a+b
}
}
}
func Take[T any](seq iter.Seq[T], n int) iter.Seq[T] {
return func(yield func(T) bool) {
if n <= 0 {
return
}
count := 0
for v := range seq {
if !yield(v) {
return
}
count++
if count == n {
return
}
}
}
}
func main() {
for n := range Take(Fib(), 10) {
fmt.Print(n, " ")
}
fmt.Println()
}0 1 1 2 3 5 8 13 21 34
An iter.Seq[T] is a function that calls yield for each value; yield returns false when the loop body breaks. Iterators let you process sequences lazily, even infinite ones, without building a slice first.
When to use generics
Use them for general-purpose code over collections and containers: helpers like Map and Filter, data structures (stacks, queues, caches, sets), and functions that work the same for any ordered or numeric type.
Don't reach for them when an interface does the job. If the function only calls methods (Write, String, Area), accept an interface. And don't make code generic "just in case": start concrete, and generalise when you have the second or third real use.
Practice
- Write
func Contains[T comparable](s []T, v T) bool. - Write a generic
Set[T comparable]type withAdd,HasandLen, usingmap[T]struct{}. - Write
func Reduce[T, A any](s []T, start A, f func(A, T) A) Aand use it to sum a slice and to join strings. - Write an iterator
Range(start, end, step int) iter.Seq[int]and loop over it.
1.What does func Max[T cmp.Ordered](s []T) T mean?
2.Which constraint do you need for a type used as a map key?
3.What does ~int64 allow in a constraint?
4.A function only calls w.Write(...). Generics or an interface?