---
title: "Generics in Go: one function, many types"
slug: "generics"
description: "Write one function for many types with type parameters, constraints such as cmp.Ordered and your own union, and a generic Stack type. Fix a constraint error."
published: "2026-12-03"
updated: "2026-12-03"
canonical: "https://aifree.dev/courses/learn-go/generics"
---

# Generics in Go: one function, many types

How do you write a function once for many types?

## Predict

```go
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"))
}
```

What does this program print?

- It does not compile, because Max is used with two different types
- 7, then banana
- 7, then apple

Answer: 7, then banana — Ints compare as numbers and strings compare in alphabetical order, so 7 and banana win.

Output:

```
7
banana
```

The compiler infers T from the arguments. cmp.Ordered allows the > operator on both ints and strings.

## Type parameters

A function can take **type parameters** in square brackets: `func Max[T cmp.Ordered](a, b T) T`. `T` is a stand-in type. The part after it is a **constraint**: it says which types are allowed. Most of the time Go infers `T` from the arguments, so you call `Max(3, 7)` with no brackets. `any` allows every type. `comparable` allows types you can compare with `==`.

## Map and Filter

```go
package 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 }))
}
```

Output:

```
[1 4 9 16 25]
[1 3 5]
```

`Map` has two type parameters, `T` for the input and `U` for the output. Go infers both from the arguments.

Playground: https://go.dev/play/p/lkbvuePHxqg

## 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 as `type 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)`.

## Sum and a generic Stack

```go
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
}

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)
}
```

Output:

```
6
4
b true
"" false
```

`var zero T` gives the zero value of whatever `T` is. `Pop` returns it with false when the stack is empty.

Playground: https://go.dev/play/p/M6QYVBOAF5A

## Fix it

```go
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"}))
}
```

Why does the compiler reject this call to Sum?

- Sum can only be called with one element
- Sum needs a type argument in square brackets
- string is not in the Number constraint, so T cannot be string

Answer: string is not in the Number constraint, so T cannot be string — Number allows only ~int and ~float64. Call Sum with numbers.

Compiler message:

```
string does not satisfy Number (string missing in ~int | ~float64)
```

Fixed:

```go
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([]int{4, 5}))
}
```

Output:

```
9
```

## Say it back

In your own words: what is a constraint on a type parameter?

Our sentence: A constraint is an interface that says which types may be used for a type parameter, and so which operations the function body can use on it.

## Mission (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.

```sh
go run .
```

## 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.
