Generics
Course contents (17 lessons)
- Getting started with Go
- Installing Go 1.25 and your first program
- Variables, types and constants
- Control flow: if, for and switch
- Functions, multiple returns and defer
- Slices and maps
- Arrays and slices
- Maps and working with strings
- Structs, methods and interfaces
- Structs, methods and pointers
- Interfaces
- Errors, packages and generics
- Error handling the Go way
- Packages and modules
- Generics
- Concurrency
- Goroutines and channels
- select, timeouts and context
- Mutexes, sync and the race detector
- Testing
- Testing and benchmarks
- Building and shipping a service
- Building an HTTP JSON API with net/http
- Building and deploying a Go service
The problem generics solve
Suppose you write a function that finds the largest number in a slice of int. Tomorrow you need the same thing for float64, and the day after for string. Before Go 1.18 you either copied the function for every type or used any and gave up type safety. Generics, added in Go 1.18, let you write the code once and have the compiler check it for each type.
A generic function
package main
import (
"cmp"
"fmt"
"strings"
)
// MaxOf works for any ordered type.
func MaxOf[T cmp.Ordered](values []T) (T, bool) {
var zero T
if len(values) == 0 {
return zero, false
}
best := values[0]
for _, v := range values[1:] {
if v > best {
best = v
}
}
return best, true
}
// Map applies f to every element.
func Map[T, U any](items []T, f func(T) U) []U {
out := make([]U, 0, len(items))
for _, it := range items {
out = append(out, f(it))
}
return out
}
// Filter keeps the elements for which keep returns true.
func Filter[T any](items []T, keep func(T) bool) []T {
var out []T
for _, it := range items {
if keep(it) {
out = append(out, it)
}
}
return out
}
// Stack is a generic type.
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
}
last := s.items[len(s.items)-1]
s.items = s.items[:len(s.items)-1]
return last, true
}
func main() {
m, _ := MaxOf([]int{3, 9, 4})
fmt.Println(m)
s, _ := MaxOf([]string{"pear", "apple", "zebra"})
fmt.Println(s)
names := []string{"ali", "sara", "usman"}
upper := Map(names, strings.ToUpper)
lengths := Map(names, func(n string) int { return len(n) })
fmt.Println(upper, lengths)
long := Filter(names, func(n string) bool { return len(n) > 3 })
fmt.Println(long)
var st Stack[string]
st.Push("a")
st.Push("b")
top, _ := st.Pop()
fmt.Println(top)
}
Output:
9
zebra
[ALI SARA USMAN] [3 4 5]
[sara usman]
b
Reading the syntax
Type parameters go in square brackets after the function name: MaxOf[T cmp.Ordered]. Here T is a placeholder, and cmp.Ordered is its constraint, which lists what T must be able to do. Ordered covers all numbers and strings, anything that supports < and >. Without that constraint the compiler would not let us write v > best.
When you call the function you usually do not write the type. The compiler infers T from the arguments: MaxOf([]int{3, 9, 4}). In Map there are two type parameters, T for the input and U for the output, and both are inferred from the arguments. A generic type like Stack[T] needs the type spelled out when you declare it: Stack[string]. Methods repeat the type parameter on the receiver, as in (s *Stack[T]), but cannot add new ones of their own.
The line var zero T is the standard way to return "nothing" of any type. Every type has a zero value, so this works for all of them.
Constraints
A constraint is an interface that may also list types.
any: no requirement. You can only store, pass and compare using a function you supply.comparable: supports==and!=. Needed for map keys and for functions like "does this slice contain this value".cmp.Ordered: supports ordering operators.- Your own:
type Number interface { ~int | ~int64 | ~float64 }. The~means "any type whose underlying type is this", so a type liketype Paisa int64also qualifies.
type Number interface {
~int | ~int64 | ~float64
}
func Sum[T Number](values []T) T {
var total T
for _, v := range values {
total += v
}
return total
}
func Keys[K comparable, V any](m map[K]V) []K {
keys := make([]K, 0, len(m))
for k := range m {
keys = append(keys, k)
}
return keys
}
Do not reach for generics too early
Generics are useful, but a lot of Go code does not need them. The Go team's advice, which I agree with, is to write plain code first. Use generics when you notice you are writing the same function for several types, or when building general-purpose containers and helpers. Where a small interface would do, use the interface. A function that takes an io.Reader should stay a function taking an io.Reader, not become func F[T io.Reader](r T).
Also check the standard library before writing your own helper. The slices and maps packages already contain generic Contains, Index, Sort, Max, Keys and many more. Writing your own Map and Filter, as above, is good practice, but there is no standard Map, so teams differ on whether such helpers help readability. A plain for loop is often just as clear.
Limits to know about
- You cannot call a method that is not in the constraint. If you need
String(), put it in the constraint interface. - Methods cannot have their own type parameters.
- Type inference sometimes fails, and you need to write the type:
Sum[float64](nil).
Common mistakes
- Using any and then comparing with ==. The compiler says
incomparable types in type set. Usecomparable. - Forgetting the tilde and wondering why your named type does not satisfy the constraint.
- Making everything generic. It adds complexity. If there is only one real type, do not abstract.
Try it yourself
Write a generic function Contains[T comparable](items []T, target T) bool and test it with ints and strings. Then write a generic Cache[K comparable, V any] type with Get and Set methods backed by a map, and use it once with string keys and once with int keys. Finally, replace your Contains with slices.Contains and confirm that the result is the same.
package main
import (
"cmp"
"fmt"
"strings"
)
// MaxOf works for any ordered type.
func MaxOf[T cmp.Ordered](values []T) (T, bool) {
var zero T
if len(values) == 0 {
return zero, false
}
best := values[0]
for _, v := range values[1:] {
if v > best {
best = v
}
}
return best, true
}
// Map applies f to every element.
func Map[T, U any](items []T, f func(T) U) []U {
out := make([]U, 0, len(items))
for _, it := range items {
out = append(out, f(it))
}
return out
}
// Filter keeps the elements for which keep returns true.
func Filter[T any](items []T, keep func(T) bool) []T {
var out []T
for _, it := range items {
if keep(it) {
out = append(out, it)
}
}
return out
}
// Stack is a generic type.
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
}
last := s.items[len(s.items)-1]
s.items = s.items[:len(s.items)-1]
return last, true
}
func main() {
m, _ := MaxOf([]int{3, 9, 4})
fmt.Println(m)
s, _ := MaxOf([]string{"pear", "apple", "zebra"})
fmt.Println(s)
names := []string{"ali", "sara", "usman"}
upper := Map(names, strings.ToUpper)
lengths := Map(names, func(n string) int { return len(n) })
fmt.Println(upper, lengths)
long := Filter(names, func(n string) bool { return len(n) > 3 })
fmt.Println(long)
var st Stack[string]
st.Push("a")
st.Push("b")
top, _ := st.Pop()
fmt.Println(top)
}
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account