Go Generics Explained with Examples

Updated 4 min read
Go Generics featured image: cards showing a type parameter, a constraint and a generic Stack

Go generics let you write one function or type that works with many data types, without copying code. In this post, you will learn type parameters, constraints and generic types, plus when to skip generics. Each idea comes with a short example that you can run yourself.

Generics build on two earlier ideas. First, constraints are interfaces, which you learned in interfaces in Go with examples. Second, most generic code works on lists, so a refresher on slices and arrays in Go will help.

What Are Go Generics?

Generics arrived in Go 1.18. They let a function take a type as a parameter, just like it takes values. In other words, you write the logic once and Go fills in the real type when you call it.

Think of a cookie cutter. The shape stays the same, but you can press it into chocolate dough or plain dough. Similarly, Go generics keep the logic fixed while the data type changes.

The Problem Go Generics Solve

func MaxInt(a, b int) int {
	if a > b {
		return a
	}
	return b
}

fmt.Println(MaxInt(3, 7)) // 7

This works only for int. So for float64 or string, you would copy the same function again and again. Before generics, the other option was any, which loses type safety.

Writing Generic Functions

Type Parameters

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(2.5, 1.5))         // 2.5
fmt.Println(Max("apple", "mango")) // mango

The part in square brackets, [T cmp.Ordered], is the type parameter list. Here T is a placeholder type, and cmp.Ordered limits it to types that support < and >. Then Go works out T from the arguments, which is called type inference.

Go Generics diagram showing one generic Max function used with int, float64 and string

One generic Max function becomes a version for int, float64 or string, depending on the call.

Constraints: any and cmp.Ordered

A constraint says which types are allowed. For example, any allows every type but permits few operations. In contrast, comparable allows ==, and cmp.Ordered also allows ordering.

Custom Constraints with ~

type Number interface {
	~int | ~float64
}

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

fmt.Println(Sum([]int{1, 2, 3}), Sum([]float64{1.5, 2.5})) // 6 4

The | sign means “or”, so Number allows int or float64. Also, the ~ sign includes your own types built on them, such as type Rupees int.

Generic Types: A Stack Example

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
}

var st Stack[string]
st.Push("a")
st.Push("b")
v, ok := st.Pop()
fmt.Println(v, ok) // b true

With Go generics, structs can have type parameters too. A stack works like a pile of plates, where the last plate you add is the first you take. Notice var zero T, which gives the zero value for whatever T turns out to be.

Go Generics in the Standard Library

fmt.Println(slices.Max([]int{4, 9, 2}))               // 9
fmt.Println(slices.Contains([]string{"a", "b"}, "b")) // true

The slices and maps packages are full of ready-made generic helpers. So before you write your own, check whether the standard library already has one.

When Not to Use Go Generics

Generics add a little complexity, so use them only when they remove real duplication. If a function works with just one type, keep it plain. Likewise, if types share behaviour rather than data handling, a normal interface is often simpler.

Common Mistakes with Go Generics

Error you seeWhy it happensHow to fix it
string does not satisfy Number (string missing in ~int | ~float64)The type is not in the constraint.Pass an allowed type or widen the constraint.
invalid operation: a > bThe constraint is any, which has no >.Use cmp.Ordered.
syntax error: method must have no type parametersA method declared its own type parameter.Use a generic function instead.

The last rule surprises many people, because only types and functions can have type parameters. Generics now show up in interviews too, so try my Go interview questions and answers.

Official Resources

These pages come straight from the Go team, so they are always accurate and up to date.

Quick Recap

  • Go generics let one function or type work with many types.
  • Type parameters go in square brackets, like [T cmp.Ordered].
  • Constraints limit T, and ~int also allows types built on int.
  • Structs like Stack[T] can be generic too.
  • Check the slices and maps packages before writing your own helper.

What’s Next?

Your code is getting powerful, so it needs proof that it works. Next, we will write automatic checks with Go’s built-in testing tools.

Coming soon: Go Unit Testing Explained for Beginners