SyntaxPilot
Courses/Go Programming/Lesson 31
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

Go Programming · Lesson 31 of 89

Generics part 2: constraints and type sets

constraint interfacestype setsunion constraints~ (underlying type) tildecmp.Orderedcmp.Comparegolang.org/x/exp/constraintsno generic methods with extra type paramsgeneric type aliases (Go 1.24)when not to use genericsgenerics vs interfaces

These are the notes for Go episode 31. In episode 30 you invented generics: one function, many types. Today Raju's chai shop needs the total of a bill, and every built-in constraint fails: any can't add, comparable can only compare. So you write your own constraint interface, learn what its type set is, build it from a union (int | float64), and discover why the little ~ tilde is needed for your own types like Rupees. You combine types and methods in one constraint, use the standard cmp package (cmp.Ordered, cmp.Compare), see where Ordered came from (golang.org/x/exp/constraints), hit the rule that methods can't have their own type parameters, meet generic type aliases (Go 1.24), and finish with the big design question: generics or interfaces? Every program here runs as-is in the SyntaxPilot compiler (language: Go) with go run main.go. All outputs and errors are from real runs (Go 1.24.7, linux/amd64).

Facts and sources

  • The Go blog article "An Introduction To Generics" by Robert Griesemer and Ian Lance Taylor (22 March 2022) says: "In Go, type constraints must be interfaces." It explains interfaces as type sets, says "The vertical bar expresses a union of types", and "The expression ~string means the set of all types whose underlying type is string." Its Ordered example is imported from golang.org/x/exp/constraints and is defined as Integer|Float|~string. Its advice: use generics "where it makes sense".
  • The Go blog post "Go 1.21 is released!" (8 August 2023) lists a "New cmp package with new utilities for comparing ordered values", plus the new built-in functions min, max and clear.
  • The Go 1.24 release notes (Go 1.24 arrived in February 2025) say: "Go 1.24 now fully supports generic type aliases: a type alias may be parameterized like a defined type."

The problem: any can't add

Raju wants the total of a bill. Prices are ints today; weights in kilos are float64. A generic Sum with T any, as in episode 30:

package main

import "fmt"

func Sum[T any](xs []T) T {
    var total T
    for _, v := range xs {
        total += v
    }
    return total
}

func main() {
    prices := []int{10, 15, 25}
    fmt.Println(Sum(prices))
}

Output:

# command-line-arguments
./main.go:8:9: invalid operation: operator + not defined on total (variable of type T constrained by any)

Why it fails: any allows every type: bool, structs, maps, functions. Most of those can't be added, so Go refuses + on a T constrained by any. comparable doesn't help either: it only promises == and !=. We need a constraint that says "numbers only", and none is built in. So we build it.

Constraint interfaces and type sets

Real-life example: the guest list at a wedding. The guard lets in only names on the list.

At the wedding In Go
The guest list the type set: the set of types a constraint allows
"Bride's side OR groom's side" a union: int \| float64, any one of these types
"...and their families" the tilde: ~int, int and every type built on int

A constraint interface is an interface used as a constraint. Until now, interfaces listed only methods. In a constraint, an interface can also list types:

package main

import "fmt"

// Number is a constraint. Its type set: int, int64, float64.
type Number interface {
    int | int64 | float64
}

func Sum[T Number](xs []T) T {
    var total T
    for _, v := range xs {
        total += v
    }
    return total
}

func main() {
    fmt.Println(Sum([]int{10, 15, 25}))
    fmt.Println(Sum([]float64{1.5, 0.25}))
}

Output:

50
1.75
  • int | int64 | float64 is a union: the vertical bar means "any one of these".
  • The type set of Number is exactly {int, int64, float64}.
  • The golden rule: inside a generic function, an operation on T is allowed only if every type in the type set supports it. All three types support +, so total += v compiles now.

That's also why % would fail if float64 is in the set (floats have no %):

type Number interface {
    ~int | ~float64
}

func Mod[T Number](a, b T) T {
    return a % b
}
# command-line-arguments
invalid operation: operator % not defined on a (variable of type T constrained by Number)

The ~ tilde: your own types

Raju's code has its own type for money. From episode 19, type Rupees int creates a new defined type; its underlying type is int. It has a String method, so fmt prints it as Rs 50:

package main

import "fmt"

// Rupees is a new type. Its underlying type is int.
type Rupees int

func (r Rupees) String() string {
    return fmt.Sprintf("Rs %d", int(r))
}

type Number interface {
    int | int64 | float64
}

func Sum[T Number](xs []T) T {
    var total T
    for _, v := range xs {
        total += v
    }
    return total
}

func main() {
    bill := []Rupees{10, 15, 25}
    fmt.Println(Sum(bill))
}

Output:

# command-line-arguments
./main.go:26:20: Rupees does not satisfy Number (possibly missing ~ for int in Number)

Why it fails: Rupees is a different type from int. The guest list says int, and Rupees is not int; it's only built on int. The compiler even suggests the fix: "possibly missing ~ for int".

The fix: ~int means "int, and every type whose underlying type is int".

package main

import "fmt"

// Rupees is a new type. Its underlying type is int.
type Rupees int

func (r Rupees) String() string {
    return fmt.Sprintf("Rs %d", int(r))
}

// ~int means: int, and every type whose underlying type is int.
type Number interface {
    ~int | ~int64 | ~float64
}

func Sum[T Number](xs []T) T {
    var total T
    for _, v := range xs {
        total += v
    }
    return total
}

func main() {
    bill := []Rupees{10, 15, 25}
    fmt.Println(Sum(bill))
    fmt.Println(Sum([]int{1, 2}))
}

Output:

Rs 50
3

The result printed as Rs 50, so T really was Rupees, and Rupees kept its String method. Plain ints still work (3).

Rules for ~:

  • ~T is allowed only when T is its own underlying type (like int, string, float64, []byte). ~Rupees is an error, because Rupees is built on int.
  • Constraints in the standard library almost always use ~ so that your own types are welcome. Use it too, unless you really mean "this exact type only".

Another example, with strings:

package main

import "fmt"

type Stringish interface {
    ~string
}

func Shout[T Stringish](s T) T {
    return s + "!"
}

type Item string

func main() {
    fmt.Println(Shout(Item("chai")), len(Shout("poha")))
}
chai! 5

A type-list interface is not a normal type

package main

import "fmt"

type Number interface {
    ~int | ~int64 | ~float64
}

func main() {
    var n Number = 5
    fmt.Println(n)
}

Output:

# command-line-arguments
./main.go:10:11: cannot use type Number outside a type constraint: interface contains type constraints

Once an interface lists types (a union or a ~ term), it can only be used inside square brackets as a constraint. Interfaces with only methods, like fmt.Stringer, work in both places: as a constraint and as a normal variable type. The same applies to an inline constraint like interface{ ~string }:

cannot use type interface{~string} outside a type constraint: interface contains type constraints

Methods and types in one constraint

A constraint can list types and methods. Each line narrows the type set: the type set is the intersection (the types that pass every line).

package main

import "fmt"

// Rupees is a new type. Its underlying type is int.
type Rupees int

func (r Rupees) String() string {
    return fmt.Sprintf("Rs %d", int(r))
}

// Money: underlying type int or int64, AND a String method.
type Money interface {
    ~int | ~int64
    String() string
}

func Total[T Money](xs []T) string {
    var t T
    for _, v := range xs {
        t += v
    }
    return "Total: " + t.String()
}

func main() {
    fmt.Println(Total([]Rupees{10, 15, 25}))
}

Output:

Total: Rs 50

Now plain ints:

package main

import "fmt"

// Rupees is a new type. Its underlying type is int.
type Rupees int

func (r Rupees) String() string {
    return fmt.Sprintf("Rs %d", int(r))
}

// Money: underlying type int or int64, AND a String method.
type Money interface {
    ~int | ~int64
    String() string
}

func Total[T Money](xs []T) string {
    var t T
    for _, v := range xs {
        t += v
    }
    return "Total: " + t.String()
}

func main() {
    fmt.Println(Total([]int{10, 15, 25}))
}

Output:

# command-line-arguments
./main.go:27:22: in call to Total, T (type int) does not satisfy Money (missing method String)

int is in the "family" of ~int, but has no String method, so it fails the second line.

Type sets at a glance

Constraint Type set
interface{ int \| float64 } exactly int and float64
interface{ ~int } int, Rupees, and every other type built on int
interface{ ~int; String() string } types built on int that also have String() string (e.g. Rupees)
fmt.Stringer (interface{ String() string }) every type with a String() string method
comparable every type that supports == and !=
any every type
interface{ int; string } nothing: no type is both, the empty type set

A constraint with an empty type set can never be satisfied:

type Empty interface {
    int
    string
}

func F[T Empty](x T) {}
cannot satisfy Empty (empty type set)

cmp.Ordered and cmp.Compare

You rarely need to write ordering constraints yourself. Go 1.21 (August 2023) added the cmp package:

  • cmp.Ordered: every type that supports <, <=, >, >=: all integer types, floats and strings, each with a ~.
  • cmp.Compare(a, b) returns -1 if a < b, 0 if equal, +1 if a > b.
  • slices.SortFunc(s, cmp) sorts a slice with a comparison function that returns a negative, zero or positive int, which is exactly what cmp.Compare returns.
  • Go 1.21 also added the built-in functions min and max, used below inside Max.
package main

import (
    "cmp"
    "fmt"
    "slices"
)

// Rupees is a new type. Its underlying type is int.
type Rupees int

func (r Rupees) String() string {
    return fmt.Sprintf("Rs %d", int(r))
}

type Order struct {
    Item  string
    Price Rupees
}

func Max[T cmp.Ordered](xs []T) T {
    m := xs[0]
    for _, v := range xs[1:] {
        m = max(m, v)
    }
    return m
}

func main() {
    fmt.Println(cmp.Compare(10, 25), cmp.Compare(25, 25), cmp.Compare("poha", "chai"))
    fmt.Println(Max([]Rupees{10, 120, 15}))
    orders := []Order{{"samosa", 15}, {"thali", 120}, {"chai", 10}}
    slices.SortFunc(orders, func(a, b Order) int {
        return cmp.Compare(a.Price, b.Price)
    })
    fmt.Println(orders)
}

Output:

-1 0 1
Rs 120
[{chai Rs 10} {samosa Rs 15} {thali Rs 120}]
  • -1 0 1: 10 < 25, 25 == 25, and "poha" comes after "chai" in alphabetical (byte) order.
  • Max of []Rupees works because cmp.Ordered uses ~, so Rupees is in its type set.
  • The orders are sorted by price, cheapest first.

Where Ordered came from: golang.org/x/exp/constraints

// golang.org/x/exp/constraints (before Go 1.21)
type Ordered interface {
    Integer | Float | ~string
}
  • When generics arrived (Go 1.18), the Go blog's examples imported Ordered from golang.org/x/exp/constraints. golang.org/x/exp is an experimental module maintained by the Go team but outside the standard library: you must add it to your go.mod (go get golang.org/x/exp), and it has no compatibility promise.
  • That package also defines smaller constraints such as Signed, Unsigned, Integer and Float, and builds Ordered as a union of constraints: a union can contain other constraint interfaces, not only single types.
  • Today: use cmp.Ordered from the standard library. You'll still see constraints.Ordered in code written before Go 1.21.

Methods can't add type parameters

package main

import "fmt"

type Stack[T any] struct {
    items []T
}

func (s *Stack[T]) Push(v T) {
    s.items = append(s.items, v)
}

// a method that adds its own type parameter U?
func (s *Stack[T]) Map[U any](f func(T) U) []U {
    var out []U
    for _, v := range s.items {
        out = append(out, f(v))
    }
    return out
}

func main() {
    var s Stack[string]
    s.Push("chai")
    fmt.Println(s.Map(func(x string) int { return len(x) }))
}

Output:

# command-line-arguments
./main.go:14:23: syntax error: method must have no type parameters

A method of a generic type may use the type's own parameters (T), but it can't declare new ones (U). One reason: Go needs to know every type's complete method set (the list of its methods) at compile time, to decide which interfaces it satisfies. A method that is really a whole family of methods, one per U, would break that.

The fix: a generic function, which can have as many type parameters as it needs:

package main

import "fmt"

type Stack[T any] struct {
    items []T
}

func (s *Stack[T]) Push(v T) {
    s.items = append(s.items, v)
}

// a generic function can have both T and U
func MapStack[T, U any](s *Stack[T], f func(T) U) []U {
    var out []U
    for _, v := range s.items {
        out = append(out, f(v))
    }
    return out
}

func main() {
    var s Stack[string]
    s.Push("chai")
    s.Push("samosa")
    fmt.Println(MapStack(&s, func(x string) int { return len(x) }))
}

Output:

[4 6]

Generic type aliases (Go 1.24)

From episode 19: type A = B (with =) is a type alias, a second name for the same type, while type A B (no =) is a defined type, a brand new type. Since Go 1.24, an alias can have type parameters:

package main

import "fmt"

// Set[T] is another NAME for map[T]struct{}: a generic type alias.
type Set[T comparable] = map[T]struct{}

// Bag[T] is a NEW defined type with the same layout.
type Bag[T comparable] map[T]struct{}

func main() {
    menu := Set[string]{"chai": {}, "poha": {}}
    _, ok := menu["chai"]
    fmt.Println(len(menu), ok)
    var m map[string]struct{} = menu // same type: no conversion needed
    fmt.Printf("%T\n", m)
    fmt.Printf("%T\n", Bag[string]{})
}

Output:

2 true
map[string]struct {}
main.Bag[string]
  • Set[string] is map[string]struct{}: it goes into a plain map variable with no conversion, and %T prints the map type.
  • Bag[string] is a new type (main.Bag[string]).
  • struct{} is the empty struct: a type with no fields that takes no memory, the usual "just a set, no value" trick from episode 15.
  • Use generic aliases to give a long generic type a short name, or when moving a type to another package without breaking old code.

When not to use generics

A receipt prints items and amounts mixed together. Both types have a String method, so a generic PrintAll[T fmt.Stringer] looks right:

package main

import "fmt"

// Rupees is a new type. Its underlying type is int.
type Rupees int

func (r Rupees) String() string {
    return fmt.Sprintf("Rs %d", int(r))
}

type Item string

func (i Item) String() string {
    return "item " + string(i)
}

func PrintAll[T fmt.Stringer](xs ...T) {
    for _, x := range xs {
        fmt.Println(x.String())
    }
}

func main() {
    PrintAll(Item("chai"), Rupees(10))
}

Output:

# command-line-arguments
./main.go:25:28: in call to PrintAll, type Rupees of Rupees(10) does not match inferred type Item for T

Why: a type parameter stands for one type per call. The first argument made T = Item, so every argument must be an Item.

The fix: no type parameter at all, just the interface:

package main

import "fmt"

// Rupees is a new type. Its underlying type is int.
type Rupees int

func (r Rupees) String() string {
    return fmt.Sprintf("Rs %d", int(r))
}

type Item string

func (i Item) String() string {
    return "item " + string(i)
}

// no type parameter: just an interface
func PrintAll(xs ...fmt.Stringer) {
    for _, x := range xs {
        fmt.Println(x.String())
    }
}

func main() {
    PrintAll(Item("chai"), Rupees(10), Item("poha"), Rupees(15))
}

Output:

item chai
Rs 10
item poha
Rs 15

An interface value can hold a different dynamic type each time (episode 21), and the right String method runs for each.

Generics vs interfaces

Use generics (type parameters) when... Use an interface when...
the same code works for many element types each type behaves its own way (its own methods)
containers: Stack[T], Set[T], trees, caches you only call methods on the value
slice and map helpers: Contains, Map, Filter, Max one list must hold different types
you need operators (+, <, ==) on the values e.g. io.Writer, fmt.Stringer, error
you want the result to keep the exact type (Sum of Rupees returns Rupees) you want the simplest possible signature

A good habit: write it for one concrete type first. When you're about to copy it for a second type, that's the moment to add a type parameter. And if a generic function only calls methods of T, rewrite it to take the interface.

Mini project: the shop's bill toolkit

Tasks: Average[T Number] returning a float64, Clamp[T cmp.Ordered] to keep a discount between 0 and 50, sorting orders by price and by name with slices.SortFunc + cmp.Compare, and a Set[T] alias with Has.

Solution
package main

import (
    "cmp"
    "fmt"
    "slices"
)

type Rupees int

func (r Rupees) String() string {
    return fmt.Sprintf("Rs %d", int(r))
}

type Number interface {
    ~int | ~int64 | ~float64
}

// Average returns the mean of xs as a float64 (0 for an empty slice).
func Average[T Number](xs []T) float64 {
    if len(xs) == 0 {
        return 0
    }
    var total T
    for _, v := range xs {
        total += v
    }
    return float64(total) / float64(len(xs))
}

// Clamp keeps v between lo and hi.
func Clamp[T cmp.Ordered](v, lo, hi T) T {
    return min(max(v, lo), hi)
}

type Order struct {
    Item  string
    Price Rupees
}

type Set[T comparable] = map[T]struct{}

func Has[T comparable](s Set[T], x T) bool {
    _, ok := s[x]
    return ok
}

func main() {
    bill := []Rupees{10, 15, 25, 120}
    fmt.Println(Average(bill))
    fmt.Println(Average([]float64{1.5, 2.5}))
    fmt.Println(Average([]int{}))

    fmt.Println(Clamp(70, 0, 50), Clamp(-5, 0, 50), Clamp(20, 0, 50))
    fmt.Println(Clamp("zebra", "a", "m"))

    orders := []Order{{"samosa", 15}, {"thali", 120}, {"chai", 10}, {"lassi", 30}}
    slices.SortFunc(orders, func(a, b Order) int {
        return cmp.Compare(a.Price, b.Price)
    })
    fmt.Println(orders)
    slices.SortFunc(orders, func(a, b Order) int {
        return cmp.Compare(a.Item, b.Item)
    })
    fmt.Println(orders)

    menu := Set[string]{"chai": {}, "poha": {}}
    fmt.Println(Has(menu, "chai"), Has(menu, "pizza"))
}

Output:

42.5
2
0
50 0 20
m
[{chai Rs 10} {samosa Rs 15} {lassi Rs 30} {thali Rs 120}]
[{chai Rs 10} {lassi Rs 30} {samosa Rs 15} {thali Rs 120}]
true false

float64(total) works because every type in Number's type set can be converted to float64, so the conversion is allowed on T.

Common mistakes (and the real messages)

Mistake Real message Why Fix
total += v with [T any] invalid operation: operator + not defined on total (variable of type T constrained by any) any promises no + [T Number] with a union
int \| float64 and a []Rupees argument Rupees does not satisfy Number (possibly missing ~ for int in Number) Rupees is not int ~int \| ~float64
var n Number = 5 cannot use type Number outside a type constraint: interface contains type constraints type-list interfaces only work in [ ] use a concrete type, or a method-only interface
Total([]int{...}) with Money (needs String) in call to Total, T (type int) does not satisfy Money (missing method String) every line of the constraint must hold pass Rupees, or drop the method line
a % b with floats in the type set invalid operation: operator % not defined on a (variable of type T constrained by Number) float64 has no % remove floats from the constraint
interface{ int; string } cannot satisfy Empty (empty type set) no type is both use a union int \| string
func (s *Stack[T]) Map[U any](...) syntax error: method must have no type parameters methods can't add type parameters func MapStack[T, U any](s *Stack[T], ...)
PrintAll[T fmt.Stringer](Item(...), Rupees(...)) in call to PrintAll, type Rupees of Rupees(10) does not match inferred type Item for T one type per call func PrintAll(xs ...fmt.Stringer)

Practice

  1. (Homework) Build Average, Clamp and the Set toolkit (solution: the mini project).
  2. (Homework) Remove a ~ from Number, call Sum with []Rupees and read the error.
  3. (Homework) Sort orders by item name with cmp.Compare (solution: the mini project's second sort).
  4. (Homework) Turn a generic Describe[T fmt.Stringer](x T) string into an interface version.
Solution 4
// generic version: works, but the type parameter adds nothing
func Describe[T fmt.Stringer](x T) string { return "[" + x.String() + "]" }

// interface version: simpler, and accepts mixed types in one slice
func Describe(x fmt.Stringer) string { return "[" + x.String() + "]" }

The function only calls a method, so an interface is enough.

  1. Write Product[T Number](xs []T) T and call it on []int{2, 3, 4}. Also print the type of Sum([]Kilo{1}) where type Kilo float64.
Solution 5
package main

import "fmt"

type Kilo float64

type Number interface {
    ~int | ~int64 | ~float64
}

func Sum[T Number](xs []T) T {
    var total T
    for _, v := range xs {
        total += v
    }
    return total
}

// Product multiplies all the values.
func Product[T Number](xs []T) T {
    p := T(1)
    for _, v := range xs {
        p *= v
    }
    return p
}

func main() {
    fmt.Println(Sum([]Kilo{1.5, 2}))
    fmt.Println(Product([]int{2, 3, 4}))
    fmt.Printf("%T\n", Sum([]Kilo{1}))
}

Output:

3.5
24
main.Kilo

T(1) converts the constant 1 to T, which is allowed because every type in the set can hold 1.

  1. Predict: does Half[T Number](x T) T { return x / 2 } give the same result for Half(7) and Half(7.0)?
Solution 6

No. Output: 3 3.5. With T = int, / is integer division (episode 6); with T = float64, it's real division. The same generic code uses each type's own operator.

  1. Write a constraint Text for "any type built on string" and a function Join[T Text](xs []T, sep T) T.
Solution 7
type Text interface {
    ~string
}

func Join[T Text](xs []T, sep T) T {
    var out T
    for i, x := range xs {
        if i > 0 {
            out += sep
        }
        out += x
    }
    return out
}

Join([]Item{"chai", "poha"}, ", ") returns the Item "chai, poha".

Quick quiz

1. Does this compile? (From the video.)

type Kilo float64

type Number interface {
    int | float64
}

func Sum[T Number](xs []T) T { ... }

fmt.Println(Sum([]Kilo{1.5, 2}))

A. Yes: prints 3.5 · B. No: Kilo does not satisfy Number · C. Yes: prints 3 · D. No: + not defined

Answer

B. Kilo is a new type built on float64, and the union lists float64 without a tilde. With ~float64 it compiles and prints 3.5.

2. What does the | mean inside a constraint?

Answer

A union: the type argument may be any one of the listed types (or type sets).

3. Can you write var x cmp.Ordered?

Answer

No. cmp.Ordered lists types, so it can only be used as a constraint: cannot use type ... outside a type constraint.

4. What does cmp.Compare("chai", "poha") return?

Answer

-1, because "chai" sorts before "poha".

Interview questions

  1. What is a type set? The set of types an interface allows. For a method-only interface, it's every type with those methods; for a constraint with type terms, it's the listed types (or their families with ~), intersected with any method requirements. A type argument satisfies a constraint when it is in its type set.
  2. What does ~int mean, and why is it usually needed? Every type whose underlying type is int, including int itself. Without it, user-defined types like type Rupees int are rejected, which is rarely what you want.
  3. Which operations can you use on a value of type T? Only those that every type in the constraint's type set supports: + for a numeric union, == for comparable, < for cmp.Ordered, plus the constraint's methods.
  4. Why can't a constraint with a union be used as a variable type? Go only allows interfaces with type terms as constraints; they describe sets of types for compile-time checking, not values you can store.
  5. What's the difference between comparable and cmp.Ordered? comparable allows == and != (including structs, pointers, arrays); cmp.Ordered allows <, > and friends (integers, floats, strings). Every ordered type is comparable, but not the other way round.
  6. What is golang.org/x/exp/constraints? An experimental module outside the standard library with constraints like Integer, Float, Ordered. Since Go 1.21, cmp.Ordered replaces its Ordered.
  7. Can methods have type parameters? No: method must have no type parameters. A method may use its type's parameters; for extra ones, write a generic function.
  8. What is a generic type alias? (Go 1.24) An alias with type parameters, like type Set[T comparable] = map[T]struct{}. Set[string] is identical to map[string]struct{}, not a new type.
  9. Generics or interfaces: how do you choose? Generics when the same code works on many element types and you want to keep the exact type or use operators; interfaces when behaviour differs per type, you only call methods, or one collection holds mixed types.
  10. What's an empty type set? A constraint no type can satisfy, e.g. interface{ int; string }; Go reports cannot satisfy ... (empty type set).

Glossary

Term Meaning Example
Generics writing code with type parameters: one piece of code for many types (episode 30) Sum[T Number]
Type parameter a name standing for a type to be chosen later T in [T Number]
Type argument the actual type that fills a type parameter Rupees in Sum(bill)
Constraint an interface saying which types may be type arguments, and what you may do with T Number, cmp.Ordered
Constraint interface an interface used as a constraint; it can list types as well as methods interface{ ~int \| ~float64 }
Type set the set of all types an interface allows {int, int64, float64}
Union type terms joined with \|: any one of them is allowed int \| float64
Type term one entry in a union: a type, or ~ plus a type ~int
~ (tilde) "every type whose underlying type is this one" ~int includes Rupees
Underlying type the built-in type a defined type is built on (episode 19) int for type Rupees int
Defined type a new, distinct type created with type Name T (no =) type Rupees int
Type alias a second name for an existing type, type A = B type Set[T comparable] = map[T]struct{}
Generic type alias (Go 1.24) a type alias with type parameters Set[string] is map[string]struct{}
Intersection the types that are in both sets; each line of a constraint narrows the set Money: ~int AND String()
Empty type set a constraint that no type satisfies interface{ int; string }
Method set the list of methods a type has; decides which interfaces it satisfies Rupees has String()
any alias for interface{}; every type, almost no operations [T any]
comparable built-in constraint: types supporting == and != [K comparable]
cmp package (Go 1.21) standard package for comparing ordered values import "cmp"
cmp.Ordered constraint: integers, floats, strings (with ~): types that support < and > Max[T cmp.Ordered]
cmp.Compare returns -1, 0 or +1 for a < b, a == b, a > b cmp.Compare(10, 25) → -1
slices.SortFunc sorts a slice using a comparison function returning negative, zero or positive sort orders by price
min, max built-in functions (Go 1.21) returning the smallest / largest argument max(m, v)
golang.org/x/exp experimental Go module outside the standard library, no compatibility promise golang.org/x/exp/constraints
constraints.Ordered the older Ordered constraint from x/exp/constraints, replaced by cmp.Ordered Integer \| Float \| ~string
Module a versioned collection of Go packages, listed in go.mod (episode 28) golang.org/x/exp
fmt.Stringer the interface with String() string; fmt uses it to print values Rupees.String()
Interface value a value of interface type holding some dynamic type and value (episode 21) []fmt.Stringer{Item("chai"), Rupees(10)}
Empty struct struct{}: a type with no fields, using no memory map values in a set
Integer division / on integers drops the fraction (episode 6) 7 / 2 is 3
Compile error an error found while building, before the program runs method must have no type parameters
# command-line-arguments the Go tool's name for the package built from the files given on the command line first line of each compile error

Summary

  • any can't add and comparable can only compare, so for "numbers only" you write a constraint interface.
  • A constraint's type set is the list of allowed types; a union (int | float64) allows any one of them, and ~int allows every type built on int, like Rupees.
  • Inside a generic function, you may use only what every type in the type set supports.
  • Interfaces that list types can be used only as constraints. Types and methods together mean both must hold (intersection).
  • cmp.Ordered, cmp.Compare and slices.SortFunc (Go 1.21) cover ordering; golang.org/x/exp/constraints is the older, external home of Ordered.
  • Methods can't add type parameters: write a generic function instead.
  • Generic type aliases (Go 1.24): type Set[T comparable] = map[T]struct{} is a new name, not a new type.
  • Generics vs interfaces: generics for the same code over many types (one type per call); interfaces when you only call methods or mix types.

Next episode: Iterators and range over functions. Loop over a million orders without building a giant slice, stop early with break, and invent yield, iter.Seq and iter.Pull.