Lesson 14 of 20 · Part 4: Types and abstraction
Generics
Go generics for beginners. Type parameters, constraints like any, comparable and cmp.Ordered, custom constraints with ~, generic types such as Stack[T], and when to use them.
4 min read · Updated · Beginner friendly
What you'll learn
- Understand the problem generics solve
- Write generic functions with type parameters
- Use constraints such as any, comparable, cmp.Ordered and your own
- Build a generic type, and know when not to use generics
Go added generics in version 1.18 (2022). They let you write a function or type once and use it with many types, while the compiler still checks every type for you. If you’ve read older Go material that says “Go has no generics”, this lesson brings you up to date.
The problem
Suppose you want to add up a slice of numbers. Without generics, you need one function per type:
func SumInts(nums []int) int {
total := 0
for _, n := range nums {
total += n
}
return total
}
func SumFloats(nums []float64) float64 {
total := 0.0
for _, n := range nums {
total += n
}
return total
}The two functions are identical except for the type. Using []any instead would compile, but you’d lose type safety and need type switches everywhere (lesson 13).
Your first generic function
A generic function has type parameters in square brackets, before the normal parameters:
package main
import "fmt"
func Sum[T int | float64](nums []T) T {
var total T
for _, n := range nums {
total += n
}
return total
}
func main() {
fmt.Println(Sum([]int{1, 2, 3}))
fmt.Println(Sum([]float64{1.5, 2.25}))
fmt.Println(Sum[int]([]int{10, 20})) // you can also name the type explicitly
}6
3.75
30Read Sum[T int | float64](nums []T) T as: “Sum works for some type T, which must be int or float64. It takes a slice of T and returns a T.”
Tis the type parameter. Any name works, but single capital letters are the convention.int | float64is the constraint: the set of typesTis allowed to be.- When you call
Sum([]int{1, 2, 3}), Go infers thatTisint, so you rarely need to write the type yourself.
Calling Sum with a type outside the constraint is a compile error, not a runtime surprise:
package main
func Sum[T int | float64](nums []T) T {
var total T
for _, n := range nums {
total += n
}
return total
}
func main() {
Sum([]string{"a", "b"})
}string does not satisfy int | float64Constraints
A constraint says what a type parameter must support. The most common ones are:
| Constraint | Allows | Lets you use |
|---|---|---|
any |
every type | assignment, passing values around |
comparable |
types that work with == |
==, !=, map keys |
cmp.Ordered |
numbers and strings | <, >, <=, >= |
int | float64 |
exactly those types | whatever all of them support |
any: works with every type
package main
import "fmt"
func Last[T any](items []T) (T, bool) {
if len(items) == 0 {
var zero T
return zero, false
}
return items[len(items)-1], true
}
func main() {
fmt.Println(Last([]string{"a", "b", "c"}))
fmt.Println(Last([]int{}))
}c true
0 falsevar zero T is the standard way to get the zero value of a type parameter.
comparable: when you need ==
package main
import "fmt"
func IndexOf[T comparable](items []T, target T) int {
for i, v := range items {
if v == target {
return i
}
}
return -1
}
func main() {
fmt.Println(IndexOf([]string{"go", "rust", "zig"}, "rust"))
fmt.Println(IndexOf([]int{4, 8, 15}, 16))
}1
-1cmp.Ordered: when you need < and >
package main
import (
"cmp"
"fmt"
)
func Largest[T cmp.Ordered](items []T) T {
best := items[0]
for _, v := range items[1:] {
if v > best {
best = v
}
}
return best
}
func main() {
fmt.Println(Largest([]int{3, 9, 2}))
fmt.Println(Largest([]float64{1.1, 0.5}))
fmt.Println(Largest([]string{"pear", "apple", "zucchini"}))
}9
1.1
zucchiniStrings are compared alphabetically (strictly, byte by byte), so "zucchini" is the largest.
Your own constraints
A constraint is just an interface. You can define your own to name a set of types. The ~ prefix means “this type or any type built on it”, so your own type Celsius float64 would also be accepted:
package main
import "fmt"
type Number interface {
~int | ~int64 | ~float64
}
func Average[T Number](nums []T) float64 {
if len(nums) == 0 {
return 0
}
var total T
for _, n := range nums {
total += n
}
return float64(total) / float64(len(nums))
}
type Celsius float64
func main() {
fmt.Println(Average([]int{1, 2, 3, 4}))
fmt.Println(Average([]Celsius{20, 22.5, 25}))
}2.5
22.5Generic functions with several type parameters
Functions can have more than one type parameter. Here’s a classic Map that turns a slice of one type into a slice of another:
package main
import (
"fmt"
"strconv"
"strings"
)
func Map[T, U any](items []T, f func(T) U) []U {
out := make([]U, 0, len(items))
for _, item := range items {
out = append(out, f(item))
}
return out
}
func Filter[T any](items []T, keep func(T) bool) []T {
var out []T
for _, item := range items {
if keep(item) {
out = append(out, item)
}
}
return out
}
func main() {
nums := []int{1, 2, 3, 4, 5, 6}
evens := Filter(nums, func(n int) bool { return n%2 == 0 })
labels := Map(evens, func(n int) string { return "#" + strconv.Itoa(n) })
fmt.Println(evens)
fmt.Println(strings.Join(labels, ", "))
}[2 4 6]
#2, #4, #6Generic types
Types can have type parameters too. In lesson 12 you built a stack of ints. Here is a stack that works with 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 words Stack[string]
words.Push("first")
words.Push("second")
w, _ := words.Pop()
fmt.Println(w, words.Len())
nums := &Stack[int]{}
nums.Push(42)
n, ok := nums.Pop()
fmt.Println(n, ok)
_, ok = nums.Pop()
fmt.Println(ok)
}second 1
42 true
falseWhen you use a generic type, you supply the type argument: Stack[string], Stack[int]. Methods on a generic type repeat the parameter in the receiver: func (s *Stack[T]) Push(v T).
A generic Pair type is another common example:
package main
import "fmt"
type Pair[K comparable, V any] struct {
Key K
Value V
}
func main() {
p := Pair[string, int]{Key: "age", Value: 36}
fmt.Printf("%s = %d\n", p.Key, p.Value)
}age = 36You already use generics
The slices and maps packages you met in lessons 6 and 7 are generic. That’s why slices.Contains, slices.Sort, slices.Max and maps.Keys work with any element type. Before writing your own generic helper, check whether the standard library already has it.
When should you use generics?
Use generics when:
- you are writing the same code for several types, especially functions over slices, maps and channels,
- you are building a container type such as a stack, queue, set or cache.
Don’t use generics when:
- a regular interface already does the job. If all you need is to call a method (
Area(),Write()), use an interface. - you only have one type. Write the plain version first; make it generic later if a second type appears.
A good rule of thumb: generics are for code that works the same on values of different types; interfaces are for code that calls behaviour that differs by type.
Exercises
1. Contains. Write a generic Contains[T comparable](items []T, target T) bool and test it with a slice of strings and a slice of ints.
Show solution
package main
import "fmt"
func Contains[T comparable](items []T, target T) bool {
for _, v := range items {
if v == target {
return true
}
}
return false
}
func main() {
fmt.Println(Contains([]string{"a", "b"}, "b"))
fmt.Println(Contains([]int{1, 2, 3}, 7))
}true
false(slices.Contains does exactly this, but it’s a great first generic function to write yourself.)
2. Reduce. Write Reduce[T, A any](items []T, start A, f func(A, T) A) A and use it to compute the total length of []string{"go", "is", "fun"}.
Show solution
package main
import "fmt"
func Reduce[T, A any](items []T, start A, f func(A, T) A) A {
acc := start
for _, item := range items {
acc = f(acc, item)
}
return acc
}
func main() {
words := []string{"go", "is", "fun"}
total := Reduce(words, 0, func(sum int, w string) int { return sum + len(w) })
fmt.Println(total)
}73. A generic Set. Create type Set[T comparable] struct { m map[T]struct{} } with NewSet, Add, Has and Len. (struct{} is an empty struct that takes no memory, which makes it a common choice for set values.)
Show solution
package main
import "fmt"
type Set[T comparable] struct {
m map[T]struct{}
}
func NewSet[T comparable]() *Set[T] {
return &Set[T]{m: make(map[T]struct{})}
}
func (s *Set[T]) Add(v T) { s.m[v] = struct{}{} }
func (s *Set[T]) Has(v T) bool { _, ok := s.m[v]; return ok }
func (s *Set[T]) Len() int { return len(s.m) }
func main() {
tags := NewSet[string]()
tags.Add("go")
tags.Add("web")
tags.Add("go") // duplicates are ignored
fmt.Println(tags.Len(), tags.Has("go"), tags.Has("rust"))
}2 true falseRecap
- Type parameters go in square brackets:
func Sum[T Number](nums []T) T. - A constraint limits the allowed types:
any,comparable,cmp.Ordered, or your own interface;~Tincludes types built onT. - Go usually infers type arguments for functions; generic types need them spelled out:
Stack[int]. - The
slicesandmapspackages are generic, so use them before writing your own helpers. - Prefer interfaces for differing behaviour and generics for identical code across types.
That completes Part 4. In Part 5 you’ll organise code into packages and modules.
Finished this lesson?
Your progress is saved in this browser only.