Skip to content
Tutorials Center
My learning

Topics

Lesson 56 of 147 ยท Generics

Constraints and Type Sets

Learn Go type constraints - any, comparable, cmp.Ordered, custom constraint interfaces with unions and the ~T tilde, type sets, methods in constraints and the pointer-receiver pattern.

A type parameter on its own is just a placeholder. What you can do with a value of type T depends on its constraint, the interface after the name in [T constraint]. With any, you can barely do anything. With a constraint such as cmp.Ordered, you can compare values with <. With a constraint that lists numeric types, you can add them. With a constraint that includes a method, you can call it.

This lesson explains constraints properly. You will meet the built-in any and comparable, the standard cmp.Ordered, and learn to write your own with unions (int | float64), the tilde (~int) and methods. Along the way you will see the idea behind it all: a constraint is an interface that describes a set of types. Read Generics: Type Parameters first if you have not.

A constraint is an interface

In Go, a constraint is written as an interface. Ordinary interfaces list methods: they describe which types have those methods. A constraint interface can also list types, and then it describes the set of types allowed as the type argument. Two names are predeclared:

  • any is an alias for interface{}: every type is allowed, no operations are guaranteed.
  • comparable allows every type whose values can be compared with == and !=: booleans, numbers, strings, pointers, channels, arrays and structs of comparable types, and interfaces.
Go comparable lets generic code use ==

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.

comparable is also what a map key needs, so map[T]bool is legal. Structs such as Point qualify because all their fields are comparable.

Slices, maps and functions are not comparable, and the compiler enforces that at the call:

Go A slice is not comparable (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 error is ./main.go:16:19: []int does not satisfy comparable. (Interface types do satisfy comparable since Go 1.20, but a comparison might still panic at run time if the dynamic type is uncomparable, as discussed in Interface Internals.)

cmp.Ordered

To use <, <=, > or >=, the type must be ordered: integers, floats and strings. The standard library provides the constraint cmp.Ordered for exactly that:

Go Min, Max and Clamp with cmp.Ordered

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.

Strings are ordered byte by byte, so "banana" is greater than "apple". The function cmp.Compare returns -1, 0 or +1 and is the building block for slices.SortFunc. You will not need to write Max yourself in new code: Go 1.21 added built-in min and max functions that work on any ordered type.

Writing your own constraints: type unions

When no standard constraint matches, define an interface that lists the allowed types separated by |. This is called a union. Here is a numeric constraint and a generic Sum, which finally fixes the problem from the previous lesson:

Go A Number constraint and a working Sum

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.

Why does the compiler now allow total += it? Because every type in the set supports +. The compiler checks the body against the whole set. It also explains why float64(Sum(items)) is legal: every type in Number converts to float64.

A union is a type set: the constraint Number is exactly those seven types. A type satisfies the constraint if it is in the set. Sum([]string{...}) would be rejected with string does not satisfy Number. You can combine interfaces in a union too, for example type Real interface { Integer | Float }, which is how larger sets are built.

There is no constraints package in the standard library. The older golang.org/x/exp/constraints package (with Integer, Float, Signed and Unsigned) is outside the standard library, and cmp.Ordered replaced its Ordered. For anything else, define the set you need yourself, as above.

The tilde: ~T

There is a catch. A defined type such as type Celsius float64 is a different type from float64, so it is not in a union that lists only float64:

Go Defined types need the tilde (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.

This produces ./main.go:21:19: Celsius does not satisfy Float (possibly missing ~ for float64 in Float). The compiler even suggests the fix. Writing ~float64 means "any type whose underlying type is float64", which includes Celsius. Using the tilde in constraints almost always makes them more useful:

Go ~T accepts defined types

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 result of Total(temps) is a Celsius, not a float64, because T was inferred as main.Celsius. That is a big advantage of generics over converting everything to a base type. Note how Number is built from Integer | Float.

Rule of thumb: put ~ in front of the basic types in a constraint unless you deliberately want to exclude defined types. You can only use ~ with a type whose underlying type is itself, so ~Celsius is an error; write ~float64.

Methods in constraints

Constraints can list methods, just like any interface, and they can be combined with type sets. A constraint with methods lets generic code call those methods on values of type T:

Go A constraint with a method and a type set

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.

Notice the difference between Describer, which is a plain interface that can also be used as an ordinary type, and NamedInt, which contains a type set (~int). Interfaces with type sets can only be used as constraints, never as the type of a variable:

Go Constraint interfaces are not ordinary 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 compiler answers ./main.go:10:8: cannot use type Number outside a type constraint: interface contains type constraints. That is the reason: a type set says which types are allowed, but a variable needs one specific type.

Constraints that reference the type parameter

A constraint can refer to the type parameter itself. This lets you express "T must have a method that works on another T", as in a generic Max over values that compare themselves:

Go A self-referential constraint

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.

Comparer[T] is a generic interface; T Comparer[T] is how a type parameter says "I am a type that can compare with myself". It is the same idea as Comparable<T> in other languages.

The pointer-receiver pattern

One idiom is worth knowing because it solves a common puzzle: you want a generic function that creates a T and then calls a pointer-receiver method on it. The method set of T does not include pointer methods, so a plain T Setter constraint will not work. The trick adds a second type parameter PT that must be a pointer to T:

Go Calling a pointer method on a fresh T

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.

You write only ParseAll[Meters], because the compiler infers PT as *Meters from the constraint (this is called constraint type inference). It looks unusual, but it is a well-known pattern.

Type sets in one picture

Every constraint is a set of types, and satisfying it means being a member:

Constraint Allowed types Operations you get
any all types assign, pass, store, var zero T
comparable comparable types ==, !=, map keys
cmp.Ordered ints, floats, strings (and ~ variants) <, <=, >, >=, ==
~int | ~float64 types whose underlying type is int or float64 arithmetic, conversions
interface{ String() string } types with that method calling String
~int; String() string such types that also have the method both

With more than one type in a union, only operations that work for all of them are allowed. That is why you cannot use % in a generic function constrained by Number (floats do not support it), but you can with a constraint listing only integer types.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which constraint do you need to compare two values of type T with <?

    comparable only allows == and !=. Ordering operators need an ordered type set such as cmp.Ordered (integers, floats and strings).
  2. 2. What does ~float64 mean in a constraint?

    The tilde widens the set to every type with float64 as its underlying type, so defined types qualify too.
  3. 3. Why does var n Number = 5 fail when Number is interface{ ~int | ~float64 }?

    A union describes several possible types, so it cannot be the type of one variable. It is only valid in a type parameter list.
  4. 4. Given func Total[T int | float64](x []T) T, which call fails to compile?

    string is not in the type set int | float64, so the call is rejected.
  5. 5. Why can't Index[T comparable] be called with a [][]int?

    Slices cannot be compared with ==, so []int does not satisfy comparable, and the compiler rejects the instantiation.

Summary

  • A constraint is an interface that describes the set of allowed type arguments and the operations the body may use.
  • any allows everything; comparable allows == and map keys; cmp.Ordered allows < and friends for ints, floats and strings.
  • Define your own constraints with unions (int | float64), and add ~ (as in ~int) to include defined types with that underlying type.
  • Constraints can also list methods, and combine methods with type sets.
  • Interfaces that contain type sets can be used only as constraints, not as variable types.
  • Constraints may refer to the type parameter itself (T Comparer[T]), and the PT interface{ *T; Method() } pattern lets generic code call pointer-receiver methods.
  • Only operations valid for every type in the set are allowed in the body.

Next: Generic Types and Methods applies type parameters to structs, stacks, sets and caches.