Generics in Go: one function, many types
Learn Go · Beginner · 10 min · After Interfaces in Go: behaviour without classes
How do you write a function once for many types?
1Guess
package main import ( "cmp" "fmt" ) func Max[T cmp.Ordered](a, b T) T { if a > b { return a } return b } func main() { fmt.Println(Max(3, 7)) fmt.Println(Max("apple", "banana")) }2Read
Type parameters
A function can take type parameters in square brackets:
func Max[T cmp.Ordered](a, b T) T.Tis a stand-in type. The part after it is a constraint: it says which types are allowed. Most of the time Go infersTfrom the arguments, so you callMax(3, 7)with no brackets.anyallows every type.comparableallows types you can compare with==.3Code
Map and Filter
1 / 2package main import "fmt" 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 main() { nums := []int{1, 2, 3, 4, 5} fmt.Println(Map(nums, func(n int) string { return fmt.Sprint(n * n) })) fmt.Println(Filter(nums, func(n int) bool { return n%2 == 1 })) }Read the program. What will it print?
4Read
Your own constraints and types
A constraint is an interface. It can list types with a union:
type Number interface { ~int | ~float64 }. The~also allows types built on them, such astype Celsius float64. A generic type takes parameters too:type Stack[T any] struct { items []T }. Methods repeat the parameter in the receiver:func (s *Stack[T]) Push(x T).5Code
Sum and a generic Stack
1 / 2package main import "fmt" type Number interface { ~int | ~float64 } func Sum[T Number](xs []T) T { var total T for _, x := range xs { total += x } return total } 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 } last := s.items[len(s.items)-1] s.items = s.items[:len(s.items)-1] return last, true } func main() { fmt.Println(Sum([]int{1, 2, 3})) fmt.Println(Sum([]float64{1.5, 2.5})) var s Stack[string] s.Push("a") s.Push("b") v, ok := s.Pop() fmt.Println(v, ok) s.Pop() v, ok = s.Pop() fmt.Printf("%q %t\n", v, ok) }Read the program. What will it print?
6Fix
package main import "fmt" type Number interface { ~int | ~float64 } func Sum[T Number](xs []T) T { var total T for _, x := range xs { total += x } return total } func main() { fmt.Println(Sum([]string{"a", "b"})) }7Say it back
8Mission · 10 min
Write Contains[T comparable](xs []T, x T) bool. Call it with a slice of ints and a slice of strings and print the results.
go run .
Free AI coding tools to practise with
- AgentRouter Free Credits
Free AI coding credits: $25 per daily check-in and $50 per invite
No cardVerified
- Cline Free Models
Try select models free in Cline via rotating promotions with a usage quota
No cardVerified
Common questions
- When should I use generics in Go?
- Use them when the same code must work for several types and the body does not depend on which one, such as Map, Filter, Max or a Stack. If you only have one type, or the types share behaviour that a small interface can describe, plain code or an interface is simpler. Do not add type parameters before you see duplication.
- What does ~int mean in a Go constraint?
- The tilde means any type whose underlying type is int, not only int itself. So a type you declare as type Age int satisfies ~int, but it would not satisfy a constraint that lists plain int. Constraints such as Number use ~int and ~float64 so that your own named number types work with generic functions like Sum.
- What is the difference between any and comparable?
- The any constraint allows every type, but the function body can then do very little with a value of that type. The comparable constraint allows only types that support == and !=, such as numbers, strings and structs of them. Use comparable when you must compare values, for example to search a slice or to use them as map keys.
Sources
- https://go.dev/doc/tutorial/generics (read 2026-12-03)
- https://go.dev/ref/spec#Type_parameter_declarations (read 2026-12-03)
- https://pkg.go.dev/cmp (read 2026-12-03)
Measured with go1.27.4 darwin/arm64 on 2026-12-03
Published Dec 3, 2026 · Updated Dec 3, 2026