Skip to content
Tutorials Center
My learning

Topics

Lesson 55 of 147 ยท Generics

Generics: Type Parameters

Learn Go generics from scratch - why they were added in 1.18, generic functions, type parameters, type inference, multiple type parameters, instantiation and generic Map, Filter and Reduce.

Some functions do not care what kind of data they handle. Finding the first element of a slice, reversing it, checking whether it contains a value or turning every element into something else works the same way for ints, strings and users. Until Go 1.18, you had two unattractive options: write the same function once per type, or accept any and lose type safety. Go 1.18 (March 2022) added generics, which let you write the function once with type parameters and have the compiler check it for every type you use.

Generics are how slices.Contains, maps.Keys, sync/atomic.Pointer[T] and cmp.Compare are written, so you have been using them already. This lesson covers generic functions: the syntax, type inference, multiple type parameters, and the classic Map, Filter and Reduce helpers. The next two lessons cover constraints and generic types, and Generics in Practice discusses when generics are the right tool.

Life before generics

Suppose you need the larger of two numbers. Without generics you either duplicate the function for each type, or use any:

Go The two old workarounds

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Copying the function per type is tedious and error-prone. The any version compiles for anything but crashes for a slice of strings, and it hands back an any that the caller must assert. Generics remove both problems.

Your first generic function

Type parameters go in square brackets after the function name, before the ordinary parameters. Each has a name and a constraint that says which types are allowed. For now we will use the constraint any, which allows every type:

Go A generic function and its two instantiations

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Read First[T any](items []T) (T, bool) as: "for any type T, take a slice of T and return a T and a bool". The call First([]int{...}) makes the compiler substitute int for T, so n is a real int, with no assertions. The line var zero T shows the standard way to produce a zero value of a type parameter.

Each use with a concrete type is called an instantiation. The compiler checks the generic body once against the constraint, then generates (or shares) the machine code for the types you actually use.

Type inference

You usually do not write the type argument. The compiler infers T from the arguments, as in First([]int{10, 20}). When inference is not possible, or you want to be explicit, supply the type arguments in brackets:

Go Inferred and explicit type arguments

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Several things happen here:

  • Zero[string]() has no arguments to infer from, so the type argument is required.
  • With Pair[float64, any](1, "one") the untyped constant 1 becomes a float64, which prints as 1.
  • Instantiating without calling (Pair[bool, bool]) gives an ordinary function value, whose type is func(bool, bool) string.
  • You can give a partial list of type arguments: leading ones explicit, the rest inferred. Pair[int](1, "x") works.

When inference fails, the compiler tells you:

Go Inference failure (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The compiler reports ./main.go:11:18: in call to Zero, cannot infer T (declared at ./main.go:5:11). The first position is the call, the second is the type parameter. Add the missing type argument, as in Zero[int](), to fix it.

Mismatched arguments

When the same type parameter appears in several parameters, all of those arguments must agree:

Go One T, two different types (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The last call fails with ./main.go:12:23: in call to Equal, mismatched types untyped int and untyped string (cannot infer T). The first two lines never run because the compile error stops the build. Here comparable is a constraint that allows ==; the next lesson explains it. The point to remember: one type parameter means one type per call.

What you can do with a type parameter

Inside a generic function, the compiler only lets you do things that are legal for every type allowed by the constraint. With any, that is very little: you can declare variables, assign, pass values around, take addresses, and store them in slices and maps. You cannot use +, < or ==:

Go any allows no operators (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The build fails with ./main.go:8:3: invalid operation: operator + not defined on total (variable of type T constrained by any). Whoever calls Sum could pass a []bool, where + makes no sense, so the compiler rejects the body. The cure is a stricter constraint that allows numbers, which is the subject of Constraints and Type Sets. Until then, the way to do operations on T is to receive them as function parameters, as the next section shows.

Multiple type parameters: Map, Filter and Reduce

Type parameters are most powerful when they describe the relationship between inputs and outputs. Mapping a slice of T to a slice of U needs two:

Go Generic Map, Filter and Reduce

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Look at what inference does with Map(words, func(w string) int {...}): from the first argument it learns T = string, from the function literal it learns U = int, so the result is a []int. strings.ToUpper is passed directly, because its type func(string) string fits func(T) U with T = U = string. The Reduce helper has an accumulator type A separate from the element type T, which is what makes it flexible: you can fold ints into a string or words into a count.

Notice that Sum failed but Reduce works with any. Reduce does not use + itself; the caller supplies the combining function. Passing behavior as a function is the generic code's way around "no operators on any".

Since Go 1.21 the standard library already has slices.IndexFunc, slices.ContainsFunc, slices.DeleteFunc and friends (see The slices and maps Packages), but it deliberately has no Map, Filter or Reduce over slices; Go style often prefers a plain for loop. Writing them yourself is a good exercise, and for lazy pipelines see Iterators.

Generic functions over maps and channels

Type parameters can appear in any type position, including maps, channels and function types. A common pattern is a helper that works with every key and value type:

Go Keys, a set of values and a merge

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The constraint on the key type is comparable, because map keys must support ==. (slices.Sorted(maps.Keys(m)) in the standard library gives you the same thing sorted.) Generic code is fully compatible with maps, channels and the other collections.

Generics are checked, not magic

A few facts to keep in mind as you start writing generic code:

  • The body is type-checked once, against the constraint, not separately for each type. That is why total += it fails for any even if you only ever pass ints.
  • Type parameters are not available as values at run time. You cannot write switch T { ... }, though you can inspect a value with any(x).(type).
  • A generic function can call other generic functions, passing its type parameters along.
  • Methods of a generic type use the type parameters of their receiver. Since Go 1.27 a method can also declare its own, but a generic function works in every version, and Generic Types and Methods covers both.
  • Don't reach for generics when an ordinary interface already expresses what you need: Interfaces remain the right tool for behavior that differs per type.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In func Last[T any](items []T) T, what does T stand for?

    T is a type parameter. Every call instantiates it with a concrete type, either inferred from the arguments or written explicitly.
  2. 2. Which call compiles?

    func Zero[T any]() T { var z T; return z }

    Zero has no arguments to infer T from, so the type argument must be written: Zeroint. Zero() fails with 'cannot infer T', and Zero(5) passes an argument the function does not take.
  3. 3. Why does total += item fail inside func Sum[T any](items []T) T?

    The body is checked against the constraint. Since any includes types without +, the operator is rejected. A numeric constraint is needed.
  4. 4. What is the type of r in r := Map([]string{"a"}, func(s string) int { return len(s) }) for func Map[T, U any](items []T, f func(T) U) []U?

    T is inferred as string from the slice and U as int from the function's result, so the result is []int.
  5. 5. What does Pair[bool, bool] (without parentheses) produce?

    Instantiating a generic function without calling it gives an ordinary function value with concrete parameter types.

Summary

  • Generics (Go 1.18) let you write a function once for many types; type parameters go in square brackets: func Name[T any](x T) T.
  • Each use with concrete types is an instantiation; the compiler usually infers the type arguments, and you write them explicitly (Zero[int]()) when it cannot.
  • A type parameter's constraint decides what the body may do; any allows almost nothing, so pass behavior as function arguments or use a stricter constraint.
  • Several type parameters describe relationships between inputs and outputs, as in Map[T, U any] and Reduce[T, A any].
  • One type parameter means one type per call: Equal(1, "a") does not compile.
  • Zero values of a type parameter are written var zero T.
  • Generic code is type-checked once, against the constraint, and generic methods (Go 1.27) can add their own type parameters only on concrete types, not in interfaces.

Next: Constraints and Type Sets shows how to allow operators like + and < on type parameters.