liveBook · Manning

Type constraint

As explained in 100 Go Mistakes and How to Avoid Them

A constraint is a Go interface type that restricts the types permitted as generic type arguments.

A type constraint is an interface type that restricts which types may be supplied as generic type arguments. For a generic map-key function, comparable permits keys usable with == or !=, unlike any, which would allow invalid slice keys. section 2.9.1

func getKeys[K comparable, V any](m map[K]V) []K {   #1
    var keys []K                                     #2
    for k := range m {
        keys = append(keys, k)
    }
    return keys
}

A comparable constraint lets getKeys accept any comparable key type while leaving the value type unrestricted. section 2.9.1

Choose the constraint according to the permitted type set:

  • Use comparable when every comparable key type is acceptable. section 2.9.1
  • Define a custom interface constraint with a union such as ~int | ~string when the set must be narrower. section 2.9.1
  • Use ~int rather than int when named types with int as their underlying type should also satisfy the constraint. section 2.9.1
  • Combine an underlying-type approximation with methods when accepted custom types must also provide behavior such as String() string. section 2.9.1

Inference at the call site

Given a map[string]int, getKeys(m) infers string as the key type; getKeys[string](m) states that type argument explicitly. section 2.9.1

How 100 Go Mistakes and How to Avoid Them covers it

How deep it goes
Explains comparable keys, custom unions, underlying-type approximation, and method intersections, stopping before broader generic design.
Examples
Uses generic getKeys, invalid slice map keys, customConstraint, explicit type arguments, and a customInt String method.
What it assumes
Assumes familiarity with Go maps, interfaces, generic type parameters, and comparable values.
What you can do after
Build it from scratch by defining constraints that prevent invalid generic calls and express permitted type sets.
How it connects
Connects type parameters with interfaces, comparable types, union operators, underlying types, methods, maps, and generic functions.

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 100 Go Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.