liveBook · Manning

Union interface

As explained in 100 Go Mistakes and How to Avoid Them

The union operator | combines type terms in a Go generic constraint to permit multiple alternative types.

A custom constraint interface can use the union operator | to permit alternative type terms. For example, ~int | ~string accepts types whose underlying type is int or string, rather than every comparable type. The union narrows which type arguments a generic function may receive. section 2.9.1

Restricting a generic map helper

Define customConstraint with ~int | ~string, then use it as the key parameter constraint for getKeys. A map[string]int is accepted, and Go can infer string as the type argument. Replacing the union with int or string changes whether named types with those underlying types are admitted. section 2.9.1

type customConstraint interface {
    ~int | ~string                   #1
}
 
func getKeys[K customConstraint,     #2
         V any](m map[K]V) []K {
    // Same implementation
}

Shows the union constraint and its placement on the generic getKeys function. section 2.9.1

How 100 Go Mistakes and How to Avoid Them covers it

How deep it goes
Defines union syntax through getKeys and contrasts exact types with underlying-type approximations using ~.
Examples
Uses customConstraint, ~int | ~string, and the generic getKeys map helper.
What it assumes
Assumes familiarity with generics, type parameters, maps, and interface-based constraints.
What you can do after
Apply it via Go generic constraints to admit selected alternative key types in reusable functions.
How it connects
Connects generic constraints with type parameters, interfaces, and underlying 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 100 Go Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.