TExcelTAD
Home › Go › Go Generics

Go Generics

Generics (added in Go 1.18) let you write functions and types that work with many types while staying fully type-checked. Before generics, you either duplicated code for int, float64, string… or used any and lost type safety. Now you declare type parameters in square brackets.

A generic function

go · try it yourself
package main

import "fmt"

// Map applies f to every element of s.
func Map[T, U any](s []T, f func(T) U) []U {
	out := make([]U, 0, len(s))
	for _, v := range s {
		out = append(out, f(v))
	}
	return out
}

func main() {
	nums := []int{1, 2, 3}
	squares := Map(nums, func(n int) int { return n * n })
	labels := Map(nums, func(n int) string { return fmt.Sprintf("#%d", n) })

	fmt.Println(squares, labels)
	fmt.Printf("%T %T\n", squares, labels)
}
[1 4 9] [#1 #2 #3]
[]int []string

[T, U any] declares two type parameters. any is their constraint — it means "any type at all". When you call Map, Go usually infers T and U from the arguments, so you don't have to write Map[int, string](...).

Constraints

A constraint limits which types may be used, and in return tells the compiler which operations are allowed. To use < or +, the constraint must allow only types that support those operators.

Constraint Allows Operations you can use
any every type assign, pass around
comparable types that support == ==, !=, map keys
cmp.Ordered integers, floats, strings <, >, <=, >=, ==
custom interface{ ~int | ~float64 } exactly the listed types whatever all of them support
go · try it yourself
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
}

// Number is a custom constraint: a union of types.
type Number interface {
	~int | ~int64 | ~float64
}

func Sum[T Number](values []T) T {
	var total T
	for _, v := range values {
		total += v
	}
	return total
}

type Cents int // ~int also accepts types whose underlying type is int

func main() {
	fmt.Println(Largest([]int{3, 9, 4}))
	fmt.Println(Largest([]string{"pear", "apple", "zucchini"}))
	fmt.Println(Sum([]float64{1.5, 2.25}))
	fmt.Println(Sum([]Cents{199, 250}))
}
9
zucchini
3.75
449

The ~ in ~int means "any type whose underlying type is int", which is why Cents is accepted.

Using an operator the constraint doesn't allow is a compile error:

go · try it yourself
package main

func Bigger[T any](a, b T) bool {
	return a > b
}

func main() {}
# command-line-arguments
./example.go:4:9: invalid operation: a > b (type parameter T cannot use operator >)

Generic types

Types can have type parameters too. Here is a simple stack that works for any element type:

go · try it yourself
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
	}
	last := s.items[len(s.items)-1]
	s.items = s.items[:len(s.items)-1]
	return last, true
}

func (s *Stack[T]) Len() int { return len(s.items) }

func main() {
	var books Stack[string]
	books.Push("Dune")
	books.Push("Emma")

	top, _ := books.Pop()
	fmt.Println(top, books.Len())

	nums := &Stack[int]{}
	_, ok := nums.Pop()
	fmt.Println("pop from empty:", ok)
}
Emma 1
pop from empty: false

var zero T is the idiomatic way to get the zero value of a type parameter.

Generics in the standard library

You already used generic functions without noticing: the slices and maps packages are built on generics.

go · try it yourself
package main

import (
	"fmt"
	"slices"
)

type Pair[K comparable, V any] struct {
	Key K
	Val V
}

func main() {
	scores := []int{42, 7, 19, 88}
	slices.Sort(scores)
	fmt.Println(scores, slices.Max(scores), slices.Contains(scores, 19))

	idx, found := slices.BinarySearch(scores, 42)
	fmt.Println(idx, found)

	p := Pair[string, int]{"age", 31}
	fmt.Printf("%+v\n", p)
}
[7 19 42 88] 88 true
2 true
{Key:age Val:31}

Tip: Don't reach for generics first. Write the concrete version; if you then find yourself copying it for a second type, make it generic. Interfaces remain the better tool when you need different behaviour rather than the same algorithm on different types.

Test yourself

Where are type parameters declared?

  1. In angle brackets <T>
  2. In square brackets [T any]
  3. In parentheses after the name
  4. With the generic keyword

Which constraint lets you use < on a type parameter?

  1. any
  2. comparable
  3. cmp.Ordered
  4. error

What does ~int mean in a constraint?

  1. Not int
  2. Approximately int
  3. Any type whose underlying type is int
  4. A pointer to int