liveBook · Manning

Type constraint

As explained in Learn Go with Pocket-Sized Projects

A type constraint is an interface-based restriction specifying which types may be used as a generic type argument.

A type constraint restricts which types may fill a generic type parameter. It lets one function or data structure work across multiple types while preserving the operations those types support. section 7.1.1 section 7.6

Common constraints provide progressively specific guarantees:

  • any accepts every type, making it the least-constraining option. section 7.1.1
  • comparable permits equality comparisons with ==, while constraints.Ordered permits >, <, >=, and <=. section 7.6
  • Union-based constraints list permitted types, such as int, int32, and int64. section 7.1.1
  • The ~ operator includes defined types whose underlying type matches a listed type. section 7.1.1

Constraining a summable type

type summable interface { int | int32 | int64 } permits only the listed integer types. Changing it to type summable interface { ~int | ~int32 | ~int64 } also permits defined types such as age int.

Using a constrained generic function

A function declared as func sortSlice[T constraints.Ordered](t []T) ([]T, error) can be called with sortSlice([]int{1,4,3,2}); the compiler infers T from the argument. section 7.6

How Learn Go with Pocket-Sized Projects covers it

How deep it goes
Explains any, comparable, Ordered, unions, and underlying-type matching with ~ through focused declarations and examples.
Examples
Uses prettyPrint, fmt.Stringer, summable integer unions, defined age types, and an Ordered sortSlice function.
What you can do after
Build generic declarations that restrict accepted types and enable operations such as equality, ordering, or formatted output.
How it connects
Connects constraints to generics, type inference, interfaces, defined types, and comparison operators.

Also explained in

Compare how 6 books explain type constraint →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Go with Pocket-Sized Projects. The section links point to the parts of the book it draws on.