Course › Week 3 · Real data and speed › Day 4 · lesson 18 of 42 · 15 min reading + 45–60 min practice
Generics
Write a function once for many types, with type parameters and constraints.
On this page
Some functions are the same for every type: the largest value of a slice, a count of each distinct value, a page of results. Without generics you write them once per type, or once with any and type assertions everywhere. Generics let you write them once, with the type as a parameter, and the compiler still checks every call.
Today: a generic function, constraints, a constraint of your own, a generic type, and when not to bother.
Generic functions
1. A type parameter
Max[T cmp.Ordered] declares a type parameter T in square brackets, before the normal parameters. cmp.Ordered is its constraint: T can be any type whose values can be compared with < and >.
package main
import (
"cmp"
"errors"
"fmt"
)
// Max returns the largest value, or an error for an empty slice.
func Max[T cmp.Ordered](values []T) (T, error) {
var largest T
if len(values) == 0 {
return largest, errors.New("max of an empty slice")
}
largest = values[0]
for _, v := range values[1:] {
if v > largest {
largest = v
}
}
return largest, nil
}
func main() {
nights, _ := Max([]int{3, 7, 2})
rating, _ := Max([]float64{4.5, 3.9})
guest, _ := Max([]string{"Bjorn", "Astrid", "Clara"})
fmt.Println(nights, rating, guest)
if _, err := Max([]int{}); err != nil {
fmt.Println("error:", err)
}
}
7 4.5 Clara
error: max of an empty sliceGo works out T from the argument: []int makes T an int. You can also write it: Maxfloat64. var largest T is the zero value of whatever T is, which is what the function returns with the error.
The errors are taken into _ on the first three calls only because those slices are written right there and cannot be empty; with data from outside, check them. The standard library has this function already, slices.Max, which panics on an empty slice instead.
2. A type that does not fit the constraint
A struct cannot be compared with >, so it does not satisfy cmp.Ordered, and the call does not compile:
package main
import (
"cmp"
"fmt"
)
type Booking struct {
Guest string
Nights int
}
func Max[T cmp.Ordered](values []T) T {
largest := values[0]
for _, v := range values[1:] {
if v > largest {
largest = v
}
}
return largest
}
func main() {
longest := Max([]Booking{{Guest: "Astrid", Nights: 3}, {Guest: "Bjorn", Nights: 7}})
fmt.Println(longest)
}
# hello
./main.go:24:16: Booking does not satisfy cmp.Ordered (Booking missing in ~int | ~int8 | ~int16 | ~int32 | ~int64 | ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr | ~float32 | ~float64 | ~string)The check is at the call, with the type’s name, followed by every type cmp.Ordered allows. Inside the function, the constraint is also what allows v > largest at all: without it, the compiler would not know that T has >. To find the longest booking, compare a field: the next lesson does it with a function as an argument.
3. comparable, for map keys
comparable allows == and !=, which is what a map key needs. It fits strings, numbers, booleans, pointers, and structs made of those.
package main
import "fmt"
// Count returns how many times each distinct value appears.
func Count[K comparable](values []K) map[K]int {
counts := make(map[K]int, len(values))
for _, v := range values {
counts[v]++
}
return counts
}
type Answer struct {
Question string
Score int
}
func main() {
fmt.Println(Count([]string{"INFO", "ERROR", "INFO"}))
fmt.Println(Count([]int{5, 4, 5, 5}))
fmt.Println(Count([]Answer{{"q1", 5}, {"q2", 4}, {"q1", 5}}))
}
map[ERROR:1 INFO:2]
map[4:1 5:3]
map[{q1 5}:2 {q2 4}:1]A struct of comparable fields is comparable, so Answer works as a key: two answers are equal when every field is. make(map[K]int, len(values)) gives the map room for that many keys up front, like make for a slice. A struct literal can leave out the field names, {"q1", 5}, when it gives every field in order; use the names everywhere else.
Constraints of your own
4. A union of types, and ~
A constraint is an interface. It can list types with |. ~int means “any type whose underlying type is int”, so your own named types fit too.
package main
import "fmt"
// Number is any integer or floating-point type, including named ones like Cents.
type Number interface {
~int | ~int64 | ~float64
}
// Sum adds up the values.
func Sum[T Number](values []T) T {
var total T
for _, v := range values {
total += v
}
return total
}
type Cents int64
func main() {
fmt.Println(Sum([]int{3, 7, 2}))
fmt.Println(Sum([]float64{4.5, 3.9}))
fmt.Println(Sum([]Cents{38850, 4500}))
}
12
8.4
43350Without the ~, Cents would not fit: it is a new type made from int64, not int64 itself (the structs lesson). The sum of Cents is a Cents, so the type is not lost on the way.
A union constraint like Number can only be used as a constraint, never as the type of a variable. The standard library’s cmp.Ordered is written exactly this way.
Generic types
5. A page of anything
A type can have type parameters too. Page[T] is a page of results of any type, like Laravel’s LengthAwarePaginator, but typed.
package main
import "fmt"
// Page is one page of results.
type Page[T any] struct {
Items []T
Number int
PerPage int
Total int
}
// LastPage is the number of the last page.
func (p Page[T]) LastPage() int {
if p.Total == 0 {
return 1
}
return (p.Total + p.PerPage - 1) / p.PerPage
}
type Booking struct {
ID int
Guest string
}
func main() {
page := Page[Booking]{
Items: []Booking{{ID: 1042, Guest: "Astrid"}, {ID: 1043, Guest: "Bjorn"}},
Number: 1,
PerPage: 2,
Total: 5,
}
fmt.Printf("page %d of %d: %v\n", page.Number, page.LastPage(), page.Items)
fmt.Println(page.Items[0].Guest)
}
page 1 of 3: [{1042 Astrid} {1043 Bjorn}]
Astridany as a constraint means no limit at all. When you create a value of a generic type, you name the type argument: Page[Booking]{…}. After that, page.Items[0].Guest needs no type assertion, because Items is a []Booking.
The method’s receiver repeats the parameter: (p Page[T]). Since Go 1.27 a method can also have type parameters of its own, which the next lesson uses.
When to use them
6. Interfaces first
Use generics for containers and algorithms that do the same thing whatever the type: pages, sets, caches, Max, Count. The question to ask: does the code care what T is? If it does not, a type parameter fits.
When the code calls methods on the value, a plain interface (the interfaces lesson) is simpler: func notifyAll(notifiers []Notifier) needs no type parameter. Most Go code you write will have no type parameters at all, and most of the generic code you use is in the standard library: slices, maps, cmp, sync.
Coming from PHP
<?php
/**
* @template T
*/
final class Page
{
/** @param list<T> $items */
public function __construct(public array $items, public int $total) {}
}
/** @var Page<Booking> $page */
PHP has generics only in docblocks: PHPStan and Psalm read @template T and check it, PHP itself does not. In Go the type parameter is part of the language, checked by the compiler on every build, and Page[Booking] is a real type at runtime.
PracticeA Tour of Go: generics; the Go tutorial; one generic function
Do the two pages of Generics in A Tour of Go, then the official Tutorial: Getting started with generics.
Exercise: Unique
Write Unique[T comparable](values []T) []T, which returns the values without duplicates, in the order they first appeared. Test it with ints, with strings, and with an empty slice, which must give an empty slice, not nil.
Show the solution
package main
import "fmt"
// Unique returns the values without duplicates, in the order they first appeared.
func Unique[T comparable](values []T) []T {
seen := make(map[T]bool, len(values))
result := make([]T, 0, len(values))
for _, v := range values {
if seen[v] {
continue
}
seen[v] = true
result = append(result, v)
}
return result
}
func main() {
fmt.Println(Unique([]int{3, 1, 3, 2, 1}))
fmt.Println(Unique([]string{"INFO", "ERROR", "INFO"}))
fmt.Println(Unique([]int{}) == nil, len(Unique([]int{})))
}
[3 1 2]
[INFO ERROR]
false 0Remember
- Reach for a type parameter only when the code does not care what the type is; otherwise use an interface.
- The constraint is what the function may do with
T:comparablefor==,cmp.Orderedfor<, your own union with~for arithmetic.
Tomorrow: functions as values, closures, and the slices and maps packages that use them.