liveBook · Manning

Union interface

As explained in Learn Go with Pocket-Sized Projects

A union interface is a Go generic constraint whose type set combines multiple permitted types or underlying types.

A union interface defines a generic constraint by listing the types a function may accept. This lets constrained code use operations supported by every listed type. section 7.1.1

Exact versus underlying types

A constraint such as int | int32 | int64 accepts only those three types. Replacing each type with ~int, ~int32, or ~int64 also accepts named types whose underlying types match, such as type age int. section 7.1.1

type summable interface {
    int | int32 | int64
}

Use this declaration as the starting point for a constraint that permits several integer types. section 7.1.1

type summable interface {
    ~int | ~int32 | ~int64
}

Use the tilde form when named types with matching underlying integer types must also be accepted. section 7.1.1

How Learn Go with Pocket-Sized Projects covers it

How deep it goes
Defines exact and underlying-type unions, then applies them to generic constraints without developing a broader constraint design.
Examples
Uses int, int32, int64, a named age type, and summable constraints with and without tilde syntax.
What you can do after
Apply it via Go generics to accept a deliberate set of numeric types and use their common operators.
How it connects
Connects generic constraints with type sets, underlying types, operators, and parameterized types.

Also explained in

Compare how 2 books explain union interface →

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.