liveBook · Manning

Type constraint

As explained in Go in Practice, Second Edition

A type constraint is a generic declaration that restricts a type parameter to a specified set of types.

A type constraint restricts a generic type parameter to a specified set of valid types. It replaces duplicated type-specific functions and avoids the weak guardrails of interface{} or any. Union constraints such as Cat | Dog permit only listed types, while a constraint can also describe numeric types accepted by a generic function. section 3.4 section 3.4.1

Use constraints to make generic functions both reusable and explicit:

  • Start broadly with any when the function operates only on a collection structure, such as filtering a slice through a callback. section 3.4.1
  • Remember that listed types are exact by default: a named type whose underlying type is int8 does not satisfy a constraint containing only int8. section 3.4.2
  • Prefix a type with ~ to admit named types sharing that underlying type, or use a supplied constraint such as constraints.Integer. section 3.4.2

A numeric constraint with a named type

Define a reusable operation with a constrained parameter: `type Numeric interface { ~int8 | int16 | int32 | int64 | float32 | float64 }`, then implement `func doubler[T Numeric](value T) T { return value * 2 }`. A named `Smallint int8` can pass because `~int8` includes types with int8 as their underlying type. For broader integer coverage, `constraints.Integer` reduces the declaration and accepts `Smallint`. section 3.4.2

How Go in Practice, Second Edition covers it

How deep it goes
Explains unions, exact types, underlying types, tilde approximation, and the experimental constraints package through runnable examples.
Examples
Uses Animal unions, generic slice filters, Numeric filters, named Smallint values, and constraints.Integer.
What it assumes
Assumes familiarity with Go functions, interfaces, slices, and basic types while introducing generic parameters and type sets.
What you can do after
Build generic functions that accept precise type sets and support named underlying types when constraints use approximation.
How it connects
Connects generics with interfaces, type sets, slices, named types, type approximation, and the constraints package.

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 Go in Practice, Second Edition. The section links point to the parts of the book it draws on.