Generics
What you will learn
Sometimes the logic of a function is identical for every type, and only the type changes. Generics, added in Go 1.18, let you write that logic once. This lesson explains type parameters, how constraints say what a type must be able to do, the meaning of any, comparable, and the ~ symbol, how to build a generic type such as a stack, and, just as important, when you should not use generics at all.
The problem
Suppose you want to find a value in a slice. Without generics you write one function per type:
func IndexString(values []string, target string) int { ... }
func IndexInt(values []int, target int) int { ... }
func IndexFloat(values []float64, target float64) int { ... }
The bodies are identical. Before generics, the options were copying code, or accepting any and losing type safety. A type parameter solves it properly.
A generic function
func Index[T comparable](values []T, target T) int {
for i, v := range values {
if v == target {
return i
}
}
return -1
}
Read the signature in pieces:
| Part | Meaning |
|---|---|
[T comparable] | Declares a type parameter T, and says it must satisfy the constraint comparable |
values []T | A slice whose elements all have type T |
target T | A value of that same type T |
int | The result is an ordinary int |
Use it with any suitable type:
fmt.Println(Index([]string{"go", "rust", "zig"}, "rust")) // 1
fmt.Println(Index([]int{10, 20, 30}, 20)) // 1
You do not have to write the type. Go infers T from the arguments. If you want to be explicit, you can: Index[string](names, "go").
Constraints: what T must be able to do
Inside a generic function, the compiler knows only what the constraint promises. If you try to use an operation the constraint does not allow, it refuses:
func Add[T any](a, b T) T {
return a + b // compile error
}
invalid operation: operator + not defined on a (variable of type T constrained by any)
A constraint is an interface that lists the permitted types or required methods. The most common ones:
| Constraint | Allows | Gives you |
|---|---|---|
any | Every type | Only assignment and passing around |
comparable | Types that support == and != | Equality comparisons, and use as map keys |
cmp.Ordered | Numbers and strings | <, <=, >, >= |
cmp.Ordered lives in the standard library package cmp:
func Max[T cmp.Ordered](a, b T) T {
if a > b {
return a
}
return b
}
fmt.Println(Max(3, 7)) // 7
fmt.Println(Max("apple", "pear")) // pear
Writing your own constraint
A constraint can list the exact types it accepts, joined by |:
type Number interface {
~int | ~int64 | ~float64
}
func Sum[T Number](values []T) T {
var total T
for _, v := range values {
total += v
}
return total
}
fmt.Println(Sum([]int{1, 2, 3})) // 6
fmt.Println(Sum([]float64{1.5, 2.5})) // 4
The ~ means "this type, or any defined type whose underlying type is this one". Without it, Number would reject type Score int, because Score is a different type from int. With ~int, a slice of Score values works too.
Generic types
Types can have type parameters as well. A stack is the classic example:
type Stack[T any] struct {
items []T
}
func (s *Stack[T]) Push(value T) {
s.items = append(s.items, value)
}
func (s *Stack[T]) Pop() (T, bool) {
var zero T
if len(s.items) == 0 {
return zero, false
}
last := len(s.items) - 1
value := s.items[last]
s.items = s.items[:last]
return value, true
}
Methods repeat the type parameter in the receiver, *Stack[T]. Notice var zero T, the standard way to produce "the zero value of whatever T is" when you have nothing to return. You choose the concrete type when you create a value:
var names Stack[string]
names.Push("Ada")
names.Push("Grace")
top, ok := names.Pop()
fmt.Println(top, ok) // Grace true
var numbers Stack[int]
numbers.Push(42)
A Stack[string] and a Stack[int] are separate types, and the compiler guarantees you never put a number in the string stack.
More than one type parameter
Separate them with commas. A Map function that transforms a slice from one type to another needs two:
func Map[T, U any](values []T, convert func(T) U) []U {
result := make([]U, 0, len(values))
for _, v := range values {
result = append(result, convert(v))
}
return result
}
lengths := Map([]string{"go", "gopher"}, func(s string) int { return len(s) })
fmt.Println(lengths) // [2 6]
Go infers T as string and U as int from the arguments.
Use the standard library first
Many common generic helpers already exist in the standard library, so check there before writing your own. The slices package has slices.Index, slices.Contains, slices.Sort, and slices.Max. The maps package has maps.Keys and maps.Clone. These are well tested and familiar to other Go programmers.
Generics or interfaces?
Both let one piece of code handle several types, but they suit different situations:
- Use generics when the same algorithm works on many types and you want the result to keep its concrete type, as with
Index,Map, or aStack[T]. - Use an interface when the code needs different behaviour from different types at run time, such as calling
Area()on a mix of shapes. - Use an ordinary function when only one concrete type is involved. Do not add a type parameter just because you can.
A rule of thumb from the Go team: write concrete code first, and reach for generics when you notice yourself writing the same function a second or third time with a different type.
Common mistakes
- Using
anyand then type-switching inside. An interface or two separate functions is usually clearer. - Making constraints broader than needed. Allow only the types the algorithm truly supports.
- Forgetting
~and wondering why a defined type likeScoreis rejected. - Expecting methods to have their own type parameters. A method can only use the type parameters declared on its receiver type.
- Hiding a three-line loop behind a complicated generic helper. A little repetition is often cheaper than an abstraction nobody can read.
Practice
Write a generic Map function that takes a slice of T and a conversion function from T to U, and returns a slice of U. Use it to convert a slice of integers into a slice of strings. Then write a generic Filter function that keeps only the elements for which a test function returns true.
package main
import (
"fmt"
"strconv"
)
func Map[T, U any](values []T, convert func(T) U) []U {
result := make([]U, 0, len(values))
for _, v := range values {
result = append(result, convert(v))
}
return result
}
func Filter[T any](values []T, keep func(T) bool) []T {
result := make([]T, 0, len(values))
for _, v := range values {
if keep(v) {
result = append(result, v)
}
}
return result
}
func main() {
numbers := []int{10, 15, 20, 25}
texts := Map(numbers, strconv.Itoa)
fmt.Println(texts) // [10 15 20 25]
big := Filter(numbers, func(n int) bool { return n >= 20 })
fmt.Println(big) // [20 25]
words := Filter([]string{"go", "rust", "c"}, func(s string) bool { return len(s) > 1 })
fmt.Println(words) // [go rust]
}
Map has two type parameters, because its input and output element types can differ. Go infers T as int and U as string from strconv.Itoa. Filter has one, because its output has the same element type as its input. Both functions are reused with different types without any copying. Each result slice is created with make and a starting capacity, so append does not have to reallocate as it grows.
Summary
A type parameter, written in square brackets, lets one function or type work with many types while the compiler still checks each use. A constraint states what operations the type must support: any allows everything but offers nothing, comparable gives ==, and cmp.Ordered gives ordering. The ~ in a constraint also accepts defined types built on the named type. Go infers type arguments from your call, generic types like Stack[T] are instantiated with a concrete type, and the standard slices and maps packages already cover many everyday cases. Reach for generics when the same algorithm repeats across types, and prefer interfaces or plain functions when they say it more clearly.
Official reference: An introduction to generics and the Type parameters section of the specification.
Ready to wrap up?
Mark this complete when you can explain the main idea and finish the practice task.