SyntaxPilot
Courses/Go Programming/Lesson 30
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 30 of 89

Generics part 1: type parameters

type parameterstype argumentsconstraintsanycomparablegeneric functionstype inferenceinstantiationgeneric types (Stack[T], Pair[K, V])methods on generic typeszero value of T

These are the notes for Go episode 30. Raju's chai shop app keeps asking the same question, "is this thing on the list?", for prices (ints) and for the menu (strings). In this episode you try the obvious fixes, copy-paste and a slice of any, watch them fail, and then invent one of the biggest features ever added to Go: generics. You will learn what a type parameter is (a blank for a type, like the blank on an order form), how a type argument fills it, and how a constraint says which types may fill it. You will meet the two built-in constraints any and comparable, write generic functions (Contains, Map, First), let Go work out the types for you with type inference, and see what instantiation really produces. Then you will make whole types generic: a Stack[T] (a pile of order trays, last in first out) and a Pair[K, V], with methods on generic types, and you will use var zero T to get the zero value of T. A short preview of cmp.Ordered points to episode 31. 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).

Where generics come from

From the Go blog article "An Introduction To Generics" by Robert Griesemer and Ian Lance Taylor (22 March 2022):

  • Go 1.18 added generics, which the authors call "the biggest change we've made to Go since the first open source release".
  • Generics bring three new features: type parameters for functions and types, interfaces as sets of types, and type inference.
  • Their advice: use generics where it makes sense. Not every function needs type parameters.

This episode covers type parameters and type inference. Interfaces as sets of types (writing your own constraints) is episode 31.

The problem: one idea, many copies

The shop's app keeps asking: is 15 rupees one of our prices? Is poha on the menu? The obvious way is one function for ints and the same function again for strings:

package main

import "fmt"

func containsInt(xs []int, x int) bool {
    for _, v := range xs {
        if v == x {
            return true
        }
    }
    return false
}

func containsString(xs []string, x string) bool {
    for _, v := range xs {
        if v == x {
            return true
        }
    }
    return false
}

func main() {
    prices := []int{10, 15, 25}
    menu := []string{"chai", "samosa", "vada pav"}
    fmt.Println(containsInt(prices, 15), containsString(menu, "poha"))
}
true false
  • It works: 15 is a price, poha is not on the menu.
  • But look: two functions, the same eight lines, only the type changed. Next week we need it for float64 weights, then for order IDs. Every new type means another copy.
  • Worse: when someone fixes a bug in one copy, the other copies keep the bug. Copy-paste code is called duplicated code, and it is hard to keep in sync.

Why []any fails

Idea: use any, the empty interface from episode 21. The empty interface interface{} is an interface with no methods, so every type satisfies it and a variable of that type can hold a value of any type. any is simply another name for it: the Go blog says any is a predeclared alias for the empty interface, added in Go 1.18. (An alias is a second name for the same type; predeclared means built into the language, like int or true, so you never import it.)

So: a slice of any, and an any to look for. One function for every type?

package main

import "fmt"

// one function for every type?
func contains(xs []any, x any) bool {
    for _, v := range xs {
        if v == x {
            return true
        }
    }
    return false
}

func main() {
    menu := []string{"chai", "samosa", "vada pav"}
    fmt.Println(contains(menu, "chai"))
}
# command-line-arguments
./main.go:17:26: cannot use menu (variable of type []string) as []any value in argument to contains
  • Nothing ran: this is a compile error (found while building, before the program starts). # command-line-arguments is how the Go tool names the package built from the files you listed on the command line; ./main.go:17:26 is file, line 17, column 26.
  • Why: a []string is not a []any. A single string can be put into an any, but a whole slice can't be converted, because the two slices are laid out differently in memory: each string element is the string itself, while each any element is an interface value (a type plus the value). Go won't secretly build a new slice for you.
  • You could copy every element by hand (real run):
package main

import "fmt"

func contains(xs []any, x any) bool {
    for _, v := range xs {
        if v == x {
            return true
        }
    }
    return false
}

func main() {
    menu := []string{"chai", "samosa", "vada pav"}
    items := make([]any, len(menu))
    for i, m := range menu {
        items[i] = m // copy each string into an any
    }
    fmt.Println(contains(items, "chai"))
    prices := []any{10, 15, 25}
    fmt.Println(contains(prices, "chai")) // compiles: no type safety
}
true
false
  • It runs, but look at the last line: searching a price list for the word "chai" compiles without a complaint. any throws the type away, so the compiler can no longer protect you. We want one function, but we also want to keep the types.

Type parameters: a blank on the order form

Think of the order form at Raju's counter: "2 x ____".

At the shop In Go Name
The order form "2 x ____": one form for any item, written once [T ...] after the function name: a name standing for a type chosen later type parameter
Fill in "chai": now it's a real order int, string: the type that fills the blank, chosen at the call type argument
"Only items we sell": rules for the blank any, comparable: which types may fill it, checked by the compiler constraint
  • A type parameter is a name, usually T, that stands for a type to be chosen later. It is written in square brackets right after the function's name. The bracket part, like [T comparable] or [T, U any], is the type parameter list: the blog notes that type parameter lists use square brackets, and look like ordinary parameter lists (names, then a constraint).
  • A type argument is the actual type that fills the blank: int, string. Once it is chosen, T means exactly that type everywhere in the function.
  • A constraint is the rule saying which types may be used as type arguments. Every type parameter has one. The blog says constraints must be interfaces (any and comparable are both interfaces).
  • A function with a type parameter list is a generic function. The whole feature (type parameters, constraints, inference) is called generics. A function without type parameters is an ordinary (non-generic) function.

Constraints: any and why == fails

Let's write it: Contains, then in square brackets T any. xs is a slice of T, and x is a T.

package main

import "fmt"

func Contains[T any](xs []T, x T) bool {
    for _, v := range xs {
        if v == x {
            return true
        }
    }
    return false
}

func main() {
    menu := []string{"chai", "samosa", "vada pav"}
    fmt.Println(Contains(menu, "chai"))
}
# command-line-arguments
./main.go:7:12: invalid operation: v == x (incomparable types in type set)
  • Why: any allows every type, including types that can't be compared with ==, like slices, maps and functions. So inside the function Go can't promise that == works for T.
  • The type set of a constraint is the set of all types it allows (one-line preview; episode 31 explains it fully). The type set of any is every type, and some of them are "incomparable".
  • A constraint is a promise both ways. The caller must pass a type that fits it. Inside, you may use only what the constraint guarantees for every type in it. With any, you can store, copy, pass and return a T, but not compare it, add it or order it.

comparable: types that support ==

Go has a built-in constraint for this: comparable. It allows every type whose values can be compared with == and !=: numbers, strings, booleans, pointers, and structs and arrays made only of those. Change any to comparable:

package main

import "fmt"

func Contains[T comparable](xs []T, x T) bool {
    for _, v := range xs {
        if v == x {
            return true
        }
    }
    return false
}

func main() {
    prices := []int{10, 15, 25}
    menu := []string{"chai", "samosa", "vada pav"}
    fmt.Println(Contains[int](prices, 15))
    fmt.Println(Contains(menu, "poha"))
    fmt.Println(Contains(menu, "chai"))
}
true
false
true
  • One function for prices and for the menu, and every call is still fully type checked.
  • In the first call we wrote the type argument ourselves: Contains[int](prices, 15). Type arguments go in square brackets after the function name, just like the type parameters.

Type inference

In the other two calls we did not write [string]. That is type inference: Go looks at the ordinary arguments, sees menu is a []string, matches it with xs []T, and works out that T is string. Most of the time you never write the type argument. (The blog calls this function argument type inference: inferring type arguments from the types of the function's arguments.)

Does inference let mistakes through? Search the price list for the word chai:

package main

import "fmt"

func Contains[T comparable](xs []T, x T) bool {
    for _, v := range xs {
        if v == x {
            return true
        }
    }
    return false
}

func main() {
    prices := []int{10, 15, 25}
    fmt.Println(Contains(prices, "chai"))
}
# command-line-arguments
./main.go:16:34: cannot use "chai" (untyped string constant) as int value in argument to Contains
  • T was inferred as int from prices, so x must be an int too. This is exactly the safety that any threw away.
  • An untyped constant is a literal like "chai" or 42 that has no fixed type yet; here it can't become an int.

And a type that breaks the constraint? Orders are slices of strings, and slices can't be compared with ==:

package main

import "fmt"

func Contains[T comparable](xs []T, x T) bool {
    for _, v := range xs {
        if v == x {
            return true
        }
    }
    return false
}

func main() {
    orders := [][]string{{"chai", "samosa"}, {"poha"}}
    fmt.Println(Contains(orders, []string{"poha"}))
}
# command-line-arguments
./main.go:16:25: []string does not satisfy comparable
  • T would be []string, which is not in the type set of comparable. The compiler checked the constraint at the call, at compile time. "Satisfy" means "is one of the types the constraint allows".
  • To compare whole slices, write a loop that compares element by element (the standard library's slices.Equal does this) instead of using ==.

Instantiation

What does Contains[int] actually make? Store it in a variable without calling it, and print its type with %T:

package main

import "fmt"

func Contains[T comparable](xs []T, x T) bool {
    for _, v := range xs {
        if v == x {
            return true
        }
    }
    return false
}

func main() {
    hasPrice := Contains[int] // instantiate: T = int
    fmt.Printf("%T\n", hasPrice)
    fmt.Println(hasPrice([]int{10, 15}, 10))
}
func([]int, int) bool
true
  • Contains[int] is an ordinary function, func([]int, int) bool, for ints only.
  • Supplying the type arguments is called instantiation. The Go blog describes it as two steps: first, substitute the type arguments for the type parameters everywhere in the function (int in place of T); second, verify that each type argument satisfies its constraint (int is comparable). If step two fails you get an error like []string does not satisfy comparable.
  • Think of a generic function as a recipe: "make ____ chai". Instantiation cooks it for one ingredient. Every call Contains(menu, "chai") instantiates Contains[string] behind the scenes, after inference picks the type.
  • You can't store an uninstantiated generic function in a variable: f := Contains has no type, because Go doesn't know T.

Two type parameters: Map[T, U]

A function can have more than one type parameter. Map takes a slice of T and a function from T to U, and returns a slice of U: T in, U out. [T, U any] means both T and U have the constraint any (like a, b int for ordinary parameters).

package main

import (
    "fmt"
    "strings"
)

// Map applies f to every element: T in, U out.
func Map[T, U any](xs []T, f func(T) U) []U {
    out := make([]U, 0, len(xs))
    for _, v := range xs {
        out = append(out, f(v))
    }
    return out
}

func main() {
    menu := []string{"chai", "samosa"}
    fmt.Println(Map(menu, strings.ToUpper))
    fmt.Println(Map(menu, func(s string) int { return len(s) }))
    prices := []int{10, 15}
    fmt.Println(Map(prices, func(p int) float64 { return float64(p) * 1.05 }))
}
[CHAI SAMOSA]
[4 6]
[10.5 15.75]
  • Menu in capitals: string to string. The length of each name: string to int. Prices with 5 percent tax: int to float64.
  • Go inferred both T and U every time: T from the slice, U from the result type of the function passed as f.
  • Map only needs any: it never compares or adds items, it just passes them to f.

The zero value of T: var zero T

New problem. First returns the first item of a list. But what if the list is empty? We must still return some T. We can't write 0 or "", because we don't know what T is. The answer: var zero T. Declare a variable of type T and don't set it.

package main

import "fmt"

// First returns the first element, or the zero value of T.
func First[T any](xs []T) (T, bool) {
    if len(xs) == 0 {
        var zero T
        return zero, false
    }
    return xs[0], true
}

func main() {
    fmt.Println(First([]string{"chai", "poha"}))
    fmt.Println(First([]int{}))
    v, ok := First([]string{})
    fmt.Printf("%q %v\n", v, ok)
}
chai true
0 false
"" false
  • From episode 3: every type has a zero value (0 for numbers, "" for strings, false for bool, nil for slices, maps, pointers and interfaces). var zero T gives the zero value of whatever T turns out to be.
  • %q prints a string in quotes, so the empty string shows as "".
  • Returning a value plus a bool that says "was it really there?" is the comma-ok style, like v, ok := m[key] for maps: ok is false when there was nothing, and then the value is just the zero value.

Generic types: Stack[T], the pile of order trays

Functions aren't enough. In the kitchen, order trays pile up:

In the kitchen In Go
Each new order tray goes on top of the pile Push(v T) adds to the end
You always take from the top: the last one in comes out first Pop() (T, bool) removes the last one
A pile of tickets, of cups, of numbers: the same idea Stack[string], Stack[int]
  • A stack is a collection where the last item put in is the first taken out. Programmers call this LIFO: last in, first out.
  • Since a stack of tickets and a stack of numbers are the same idea, the type itself needs a type parameter. A type with a type parameter list is a generic type.
package main

import "fmt"

// Stack is a pile: the last thing pushed is the first popped.
type Stack[T any] struct {
    items []T
}

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

func (s *Stack[T]) Pop() (T, bool) {
    var zero T
    if len(s.items) == 0 {
        return zero, false
    }
    v := s.items[len(s.items)-1]
    s.items = s.items[:len(s.items)-1]
    return v, true
}

func main() {
    var trays Stack[string]
    trays.Push("order 1: chai")
    trays.Push("order 2: poha")
    fmt.Println(trays.Pop())
    fmt.Println(trays.Pop())
    fmt.Println(trays.Pop())

    nums := Stack[int]{}
    nums.Push(42)
    fmt.Println(nums.Pop())
}
order 2: poha true
order 1: chai true
 false
42 true
  • type Stack[T any] struct { items []T } is a struct holding a slice of T.
  • Methods on generic types name the type parameter in the receiver: func (s *Stack[T]) Push(v T). The [T] there is not a new constraint; it just gives a name to the stack's type parameter so the method can use it (v T). You don't repeat any.
  • Push adds to the end; Pop takes the last one, and returns var zero T and false when the stack is empty. The receiver is a pointer (*Stack[T]) because both methods change the stack.
  • Order 2 comes out first, then order 1: last in, first out. The third Pop prints the empty string (so the line starts with a space) and false. And Stack[int] works with the same code.
  • var trays Stack[string] is ready to use: the zero value of the struct has a nil slice, and append works on nil slices.

A generic type needs its type argument

Can we leave out the type argument?

package main

import "fmt"

// Stack is a pile: the last thing pushed is the first popped.
type Stack[T any] struct {
    items []T
}

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

func (s *Stack[T]) Pop() (T, bool) {
    var zero T
    if len(s.items) == 0 {
        return zero, false
    }
    v := s.items[len(s.items)-1]
    s.items = s.items[:len(s.items)-1]
    return v, true
}

func main() {
    var trays Stack
    trays.Push("order 1: chai")
    fmt.Println(trays.Pop())
}
# command-line-arguments
./main.go:25:15: cannot use generic type Stack[T any] without instantiation
  • For a function call, Go infers T from the arguments. For var trays Stack there is nothing to infer from, so you must always write it: Stack[string].

Once it's a Stack[string], it takes only strings

Same Stack code, with this main:

func main() {
    var trays Stack[string]
    trays.Push(42)
    fmt.Println(trays.Pop())
}
# command-line-arguments
./main.go:26:16: cannot use 42 (untyped int constant) as string value in argument to trays.Push

Fully type safe, with no copy-paste.

Two parameters on a type: Pair[K, V]

A generic type can have several type parameters, each with its own constraint. Pair holds a key K, which must be comparable (so it could be used as a map key, since map keys need ==), and a value V of any type. Its String method (episode 21) makes fmt print it nicely.

package main

import "fmt"

// Pair holds a key and a value of any two types.
type Pair[K comparable, V any] struct {
    Key K
    Val V
}

func (p Pair[K, V]) String() string {
    return fmt.Sprintf("%v → %v", p.Key, p.Val)
}

func main() {
    a := Pair[string, int]{"chai", 10}
    b := Pair[int, []string]{Key: 7, Val: []string{"poha", "chai"}}
    fmt.Println(a)
    fmt.Println(b)
    fmt.Printf("%T\n", a)
}
chai → 10
7 → [poha chai]
main.Pair[string,int]
  • [K comparable, V any]: two blanks, two different rules. V may even be a slice ([]string), because V only needs any.
  • The receiver (p Pair[K, V]) names both type parameters, in the same order.
  • %T prints main.Pair[string,int]: each set of type arguments makes its own separate type. Pair[string, int] and Pair[string, float64] are as different as int and string (see the expert corner).

A preview: ordering with cmp.Ordered

One last try: Max finds the biggest price, with T any and >:

package main

import "fmt"

func Max[T any](xs []T) T {
    m := xs[0]
    for _, v := range xs[1:] {
        if v > m {
            m = v
        }
    }
    return m
}

func main() {
    fmt.Println(Max([]int{10, 25, 15}))
}
# command-line-arguments
./main.go:8:12: invalid operation: v > m (type parameter T cannot use operator >)
  • Same reason as before: any doesn't promise ordering. And comparable only promises == and !=, not bigger or smaller.

The standard library's cmp package has the constraint we need: cmp.Ordered, every type that supports <, <=, > and >= (integers, floats and strings). This is a preview only; episode 31 shows how constraints like it are written.

package main

import (
    "cmp"
    "fmt"
)

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

func main() {
    fmt.Println(Max([]int{10, 25, 15}))
    fmt.Println(Max([]float64{1.5, 0.25}))
    fmt.Println(Max([]string{"chai", "samosa", "poha"}))
}
25
1.5
samosa

samosa is the last name in alphabetical order. (This Max panics on an empty slice because of xs[0]; a safer version would return (T, bool) like First.)

Mini project: a generic shop toolkit

Build four tools for Raju's shop:

  1. Count[T comparable](xs []T, x T) int: how many chai orders? Needs comparable, because it uses ==.
  2. Filter[T any](xs []T, keep func(T) bool) []T: bills over 50. Only needs any: it never compares items itself, the keep function decides.
  3. Queue[T any] with Add and Next: first in, first out (FIFO), the opposite of our stack, like the line of customers at the counter.
  4. Last[T any](xs []T) (T, bool): var zero T when the list is empty.

Full worked solution (real run):

package main

import "fmt"

// Count says how many times x appears in xs.
func Count[T comparable](xs []T, x T) int {
    n := 0
    for _, v := range xs {
        if v == x {
            n++
        }
    }
    return n
}

// Filter keeps only the items that keep says yes to.
func Filter[T any](xs []T, keep func(T) bool) []T {
    var out []T
    for _, v := range xs {
        if keep(v) {
            out = append(out, v)
        }
    }
    return out
}

// Queue is a line: the first thing added is the first one out.
type Queue[T any] struct {
    items []T
}

func (q *Queue[T]) Add(v T) {
    q.items = append(q.items, v)
}

func (q *Queue[T]) Next() (T, bool) {
    var zero T
    if len(q.items) == 0 {
        return zero, false
    }
    v := q.items[0]
    q.items = q.items[1:]
    return v, true
}

func (q *Queue[T]) Len() int {
    return len(q.items)
}

// Last returns the last element, or the zero value of T and false.
func Last[T any](xs []T) (T, bool) {
    if len(xs) == 0 {
        var zero T
        return zero, false
    }
    return xs[len(xs)-1], true
}

func main() {
    orders := []string{"chai", "poha", "chai", "samosa", "chai"}
    fmt.Println("chai orders:", Count(orders, "chai"))

    bills := []int{30, 80, 45, 120, 50}
    big := Filter(bills, func(b int) bool { return b > 50 })
    fmt.Println("bills over 50:", big)
    long := Filter(orders, func(s string) bool { return len(s) > 4 })
    fmt.Println("long names:", long)

    var line Queue[string]
    line.Add("Asha")
    line.Add("Ravi")
    line.Add("Meena")
    fmt.Println("waiting:", line.Len())
    for line.Len() > 0 {
        name, _ := line.Next()
        fmt.Println("serve", name)
    }
    fmt.Println(line.Next())

    fmt.Println(Last(orders))
    fmt.Println(Last(bills))
    fmt.Println(Last([]float64{}))
}
chai orders: 3
bills over 50: [80 120]
long names: [samosa]
waiting: 3
serve Asha
serve Ravi
serve Meena
 false
chai true
50 true
0 false
  • Filter(bills, ...) keeps 80 and 120; 50 is not over 50. long names keeps only samosa (6 letters); chai and poha have 4.
  • The queue serves Asha first (first in, first out). Next on an empty queue returns "" and false, so the line starts with a space.
  • Last([]float64{}) returns 0 false: the zero value of float64.
  • Queue.Next takes from the front (q.items[0], then q.items[1:]); Stack.Pop takes from the back. That one difference is FIFO vs LIFO.

Expert corner

Generics vs interfaces at a glance

Interface parameter (func f(s fmt.Stringer)) Type parameter (func f[T C](x T))
What is fixed the methods a value must have the type, chosen per call
Mixing types in one slice yes: []any{"chai", 10} no: a []T holds one type
Type kept for the caller no: you get back an interface, often need a type assertion yes: First([]string{...}) returns a string
Operators like ==, > only through methods (or on any, == with a runtime risk) allowed if the constraint promises them
Good for behaviour that differs per type (String(), Price()) the same code for many types: containers (Stack[T]), slice helpers (Map, Filter)

Rule of thumb, in the spirit of the blog's "use generics where it makes sense": if you are writing the same code again with only the type changed, try a type parameter. If each type needs different behaviour, use an interface with methods.

How instantiation works

Contains[int] happens in the two steps from the blog: substitute, then verify. You can see the result of substitution with %T, even for several type parameters (real run):

package main

import "fmt"

func Map[T, U any](xs []T, f func(T) U) []U {
    out := make([]U, 0, len(xs))
    for _, v := range xs {
        out = append(out, f(v))
    }
    return out
}

func main() {
    f := Map[string, int]
    fmt.Printf("%T\n", f)
    fmt.Println(f([]string{"chai", "vada pav"}, func(s string) int { return len(s) }))
}
func([]string, func(string) int) []int
[4 8]

Every T became string and every U became int. Then Go checked that both satisfy any (always true).

Why []string isn't []any

Converting one string to any is cheap: Go wraps it. Converting a []string to []any would mean building a brand-new slice and wrapping every element, because the memory layouts differ. Go never does that work silently, so the conversion simply doesn't exist (cannot use menu (variable of type []string) as []any value). With a type parameter, []T with T = string is []string: no conversion, no copy.

Each instantiation is its own type

Pair[string, int] and Pair[string, float64] come from the same code but are different types (real run):

package main

import "fmt"

type Pair[K comparable, V any] struct {
    Key K
    Val V
}

func main() {
    a := Pair[string, int]{"chai", 10}
    var b Pair[string, float64] = a
    fmt.Println(b)
}
# command-line-arguments
./main.go:12:35: cannot use a (variable of struct type Pair[string, int]) as Pair[string, float64] value in variable declaration

comparable with structs and interfaces

A struct type satisfies comparable when all its fields are comparable. A struct with a slice field does not (real run):

package main

import "fmt"

func Contains[T comparable](xs []T, x T) bool {
    for _, v := range xs {
        if v == x {
            return true
        }
    }
    return false
}

type Combo struct {
    Name  string
    Items []string
}

func main() {
    combos := []Combo{{"breakfast", []string{"chai", "poha"}}}
    fmt.Println(Contains(combos, combos[0]))
}
# command-line-arguments
./main.go:21:25: Combo does not satisfy comparable

With type Item struct { Name string; Price int } instead, Contains(menu, Item{"poha", 25}) compiles and prints true (real run).

Interface types such as any are accepted as comparable type arguments, because == is defined on interface values. But the check then moves to run time: comparing two interface values that both hold a slice panics (real run):

package main

import "fmt"

func Contains[T comparable](xs []T, x T) bool {
    for _, v := range xs {
        if v == x {
            return true
        }
    }
    return false
}

func main() {
    things := []any{"chai", []string{"poha"}}
    fmt.Println(Contains(things, any("chai")))
    fmt.Println(Contains(things, any([]string{"poha"})))
}
true
panic: runtime error: comparing uncomparable type []string

goroutine 1 [running]:
main.Contains[...](...)
    /tmp/notes30/IFACEPANIC/main.go:7
main.main()
    /tmp/notes30/IFACEPANIC/main.go:17 +0x1d0
exit status 2
  • The first call finds "chai" before ever reaching the slice. In the second, "chai" vs a slice is simply false (different dynamic types), but slice vs slice panics. A panic is a run-time crash that stops the program (exit status 2).
  • So comparable with concrete types like int or Item is checked fully at compile time; with interface types, keep in mind that == can still panic.

Inference limits: a type parameter used only in the result

The blog notes that function argument type inference only works for type parameters used in the function's parameters, not for ones used only in the result or only in the body. Here T appears only in the result:

package main

import "fmt"

func Zero[T any]() T {
    var zero T
    return zero
}

func main() {
    fmt.Println(Zero())
}
# command-line-arguments
./main.go:11:21: in call to Zero, cannot infer T (declared at ./main.go:5:11)

There are no arguments to look at, so Go can't work out T. Write the type argument explicitly (real run):

package main

import "fmt"

func Zero[T any]() T {
    var zero T
    return zero
}

func main() {
    fmt.Println(Zero[int]())
    fmt.Printf("%q\n", Zero[string]())
    fmt.Println(Zero[bool](), Zero[[]int]() == nil)
}
0
""
false true

Partial type arguments: put the hard-to-infer one first

You may write only the first type arguments and let Go infer the rest. So put a type parameter that can't be inferred first in the list (real run):

package main

import (
    "fmt"
    "strconv"
)

// Convert turns every T into a U with f.
func Convert[U, T any](xs []T, f func(T) U) []U {
    out := make([]U, 0, len(xs))
    for _, v := range xs {
        out = append(out, f(v))
    }
    return out
}

func main() {
    prices := []int{10, 15}
    labels := Convert[string](prices, func(p int) string { return "Rs " + strconv.Itoa(p) })
    fmt.Println(labels)
    fmt.Printf("%T\n", Convert[string, int])
}
[Rs 10 Rs 15]
func([]int, func(int) string) []string

Convert[string] fixes U; T = int is inferred from prices.

Methods can't have their own type parameters

A method may use its type's parameters, but can't add new ones (real run):

package main

import "fmt"

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

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() {
    fmt.Println("never runs")
}
# command-line-arguments
./main.go:9:23: syntax error: method must have no type parameters

Write a generic function instead: func MapStack[T, U any](s *Stack[T], f func(T) U) []U.

Forgetting [T] in the receiver

The receiver must name the type parameters (real run):

package main

import "fmt"

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

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

func main() {
    fmt.Println("never runs")
}
# command-line-arguments
./main.go:9:10: cannot use generic type Stack[T any] without instantiation
./main.go:9:24: undefined: T

Fix: func (s *Stack[T]) Push(v T). You may pick a different name in the receiver (Stack[E]), but it must be there.

Common mistakes (and the real messages)

Mistake Real message Why Fix
passing menu ([]string) to a []any parameter cannot use menu (variable of type []string) as []any value in argument to contains []string is not []any func Contains[T comparable](xs []T, x T) bool
v == x with [T any] invalid operation: v == x (incomparable types in type set) any doesn't promise == [T comparable]
Contains(prices, "chai") cannot use "chai" (untyped string constant) as int value in argument to Contains T inferred as int pass an int, or search the right list
Contains(orders, []string{"poha"}) []string does not satisfy comparable slices can't use == compare with slices.Equal in a loop
a struct with a slice field in Contains Combo does not satisfy comparable every field must be comparable compare by a comparable field, e.g. Name
var trays Stack cannot use generic type Stack[T any] without instantiation a type needs its argument var trays Stack[string]
trays.Push(42) on a Stack[string] cannot use 42 (untyped int constant) as string value in argument to trays.Push T is string everywhere push a string, or use Stack[int]
func (s *Stack) Push(v T) cannot use generic type Stack[T any] without instantiation and undefined: T the receiver must name T func (s *Stack[T]) Push(v T)
v > m with [T any] invalid operation: v > m (type parameter T cannot use operator >) any doesn't promise > [T cmp.Ordered]
Zero() for func Zero[T any]() T in call to Zero, cannot infer T T used only in the result Zero[int]()
a method with its own [U any] syntax error: method must have no type parameters methods can't add type parameters a generic function
assigning Pair[string, int] to Pair[string, float64] cannot use a (variable of struct type Pair[string, int]) as Pair[string, float64] value in variable declaration each instantiation is its own type use the same type arguments

Practice

  1. (Homework) Write Count, Filter and Last, and build Queue[T] with Add and Next (solution: the mini project).
  2. (Homework) Call Contains on a [][]string and read the error.
  3. (Homework) Print %T of a Pair[int, bool].
  4. Write Index[T comparable](xs []T, x T) int that returns the position of x, or -1.
  5. Write Reverse[T any](xs []T) []T that returns a new reversed slice. Which constraint is enough, and why?
  6. Write Min for ints, floats and strings (use the preview constraint).
  7. Add a Peek() (T, bool) method to Stack[T] that looks at the top without removing it.
  8. Predict the output:
package main

import "fmt"

func Map[T, U any](xs []T, f func(T) U) []U {
    out := make([]U, 0, len(xs))
    for _, v := range xs {
        out = append(out, f(v))
    }
    return out
}

func main() {
    prices := []int{10, 15, 25}
    double := Map(prices, func(p int) int { return p * 2 })
    big := Map(prices, func(p int) bool { return p > 12 })
    fmt.Println(double, big)
    fmt.Printf("%T %T\n", double, big)
}
Solution
  1. See the mini project for the full code and its real output.

  2. Real message: ./main.go:16:25: []string does not satisfy comparable. Slices can't be compared with ==, so []string is not in the type set of comparable.

  3. Real run:

package main

import "fmt"

type Pair[K comparable, V any] struct {
    Key K
    Val V
}

func main() {
    p := Pair[int, bool]{7, true}
    fmt.Printf("%T\n", p)
    fmt.Printf("%+v\n", p)
    var q Pair[string, int]
    fmt.Printf("%+v\n", q)
}
main.Pair[int,bool]
{Key:7 Val:true}
{Key: Val:0}

%+v prints field names. The zero Pair[string, int] has an empty Key and Val 0.

4 to 7. One program with all four (real run):

package main

import (
    "cmp"
    "fmt"
)

// Index returns the position of x in xs, or -1.
func Index[T comparable](xs []T, x T) int {
    for i, v := range xs {
        if v == x {
            return i
        }
    }
    return -1
}

// Reverse returns a new slice with the items in reverse order.
func Reverse[T any](xs []T) []T {
    out := make([]T, 0, len(xs))
    for i := len(xs) - 1; i >= 0; i-- {
        out = append(out, xs[i])
    }
    return out
}

// Min returns the smallest item (cmp.Ordered: preview of episode 31).
func Min[T cmp.Ordered](xs []T) T {
    m := xs[0]
    for _, v := range xs[1:] {
        if v < m {
            m = v
        }
    }
    return m
}

// Peek looks at the top of the stack without removing it.
type Stack[T any] struct {
    items []T
}

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

func (s *Stack[T]) Peek() (T, bool) {
    var zero T
    if len(s.items) == 0 {
        return zero, false
    }
    return s.items[len(s.items)-1], true
}

func main() {
    menu := []string{"chai", "samosa", "vada pav"}
    fmt.Println(Index(menu, "samosa"), Index(menu, "poha"))
    fmt.Println(Reverse(menu))
    fmt.Println(Reverse([]int{10, 15, 25}))
    fmt.Println(Min([]int{25, 10, 15}), Min([]string{"poha", "chai"}))

    var cups Stack[int]
    fmt.Println(cups.Peek())
    cups.Push(150)
    cups.Push(250)
    fmt.Println(cups.Peek())
    fmt.Println(len(cups.items))
}
1 -1
[vada pav samosa chai]
[25 15 10]
10 chai
0 false
250 true
2
  • Index needs comparable (it uses ==). Reverse needs only any: it moves items but never compares them.
  • Peek returns the top (250) and leaves both items in place (len is still 2).
  1. Real output:
[20 30 50] [false true true]
[]int []bool

T is int both times; U is int for double and bool for big, inferred from the function passed in.

Quick quiz

1. What does this print? (From the video.)

func Last[T any](xs []T) T {
    var zero T
    if len(xs) == 0 {
        return zero
    }
    return xs[len(xs)-1]
}

fmt.Println(Last([]int{}), Last([]string{"chai", "poha"}))

A. 0 poha · B. nil poha · C. compile error · D. 0 chai

Answer

A. var zero T is the zero value of T: 0 when T is int. For the strings, the last element is "poha". Real output (inside a full package main program): 0 poha.

2. Which constraint lets you use == on T: any or comparable?

Answer

comparable. With any you get invalid operation: v == x (incomparable types in type set).

3. In Contains(menu, "chai"), nobody wrote [string]. What feature worked out T?

Answer

Type inference (function argument type inference): Go matched menu ([]string) with xs []T, so T is string.

4. What does fmt.Printf("%T\n", Contains[int]) print, for func Contains[T comparable](xs []T, x T) bool?

Answer

func([]int, int) bool. Instantiation substitutes int for T and gives an ordinary function.

5. Why does var trays Stack fail, while Contains(menu, "chai") works without type arguments?

Answer

A function call has arguments to infer T from; a type in a declaration has nothing to infer from. Real message: cannot use generic type Stack[T any] without instantiation. Write Stack[string].

6. True or false: a stack is FIFO.

Answer

False. A stack is LIFO (last in, first out), like the pile of order trays. A queue is FIFO.

Interview questions

  1. What problem do generics solve in Go? Writing the same code once for many types without losing type safety. Before Go 1.18 you had to copy code per type or use the empty interface and lose compile-time type checking (and often need type assertions).
  2. What is the difference between a type parameter and a type argument? A type parameter is the placeholder name in the declaration (T in [T comparable]); a type argument is the actual type supplied at use (int in Contains[int]), written by you or inferred.
  3. What is a constraint, and what are any and comparable? A constraint is an interface that limits which type arguments are allowed and decides which operations are allowed on T inside. any (alias for interface{}) allows every type but only basic operations; comparable allows types that support == and !=.
  4. What is instantiation? Supplying type arguments to a generic function or type. Per the Go blog, it substitutes the type arguments for the type parameters, then verifies each satisfies its constraint. The result is an ordinary function or type, e.g. func([]int, int) bool.
  5. When can't Go infer type arguments? When a type parameter is not used in the function's parameters, only in the result or the body (func Zero[T any]() T), and always for generic types in declarations (var s Stack[string]). You can give the first type arguments explicitly and let Go infer the rest.
  6. Why can't you pass a []string where []any is expected? They are different types with different memory layouts; converting would need a new slice with every element wrapped. A generic []T avoids the problem: with T = string, it is []string.
  7. How do you return "nothing" from a generic function? var zero T gives the zero value of whatever T is; return it with a false in the comma-ok style.
  8. How do methods work on generic types? Can a method have its own type parameters? The receiver names the type's parameters, e.g. func (s *Stack[T]) Push(v T). A method cannot declare new type parameters (method must have no type parameters); use a generic function instead.
  9. Generics or interfaces? Use type parameters when the same code works for many types (containers, slice helpers); use interfaces with methods when each type needs its own behaviour. The blog's advice: use generics where it makes sense.
  10. Is any always safe as a comparable type argument? It compiles, but == on interface values holding uncomparable dynamic types (like slices) panics at run time: comparing uncomparable type []string.

Glossary

Term Meaning Example
Generics the Go feature (since Go 1.18) for writing code with type parameters: one piece of code for many types Contains, Stack[T]
Duplicated code the same code copied with small changes; fixes in one copy don't reach the others containsInt and containsString
Type parameter a name standing for a type to be chosen later; the blank on the order form T in [T comparable]
Type parameter list the square-bracket list of type parameters and their constraints after a function or type name [T, U any], [K comparable, V any]
Type argument the actual type that fills a type parameter int in Contains[int]
Constraint an interface saying which types may be type arguments, and what you may do with T any, comparable, cmp.Ordered
Satisfy a type satisfies a constraint when it is one of the types the constraint allows int satisfies comparable
Type set the set of all types a constraint allows (preview; episode 31) any: every type
Empty interface interface{}, an interface with no methods; every type satisfies it (episode 21) var x interface{} = 10
any a predeclared alias for the empty interface (Go 1.18); as a constraint it allows every type [T any], []any{"chai", 10}
Alias a second name for the same type any = interface{}
Predeclared built into the language, no import needed int, any, comparable
comparable built-in constraint: types whose values support == and != [T comparable]
cmp.Ordered constraint from the cmp package: types that support <, > (ints, floats, strings); preview only func Max[T cmp.Ordered]
Generic function a function with a type parameter list func Map[T, U any](...)
Generic type a type with a type parameter list type Stack[T any] struct{...}
Type inference Go working out type arguments from the call's arguments Contains(menu, "chai") → T = string
Function argument type inference inference from the types of a function's arguments; doesn't work for T used only in results or the body Zero() → cannot infer T
Instantiation supplying type arguments: substitute them, then verify the constraints Contains[int] is func([]int, int) bool
Stack[T] a generic stack: Push on top, Pop from the top var trays Stack[string]
Stack a collection where the last item in is the first out the pile of order trays
LIFO last in, first out: how a stack works order 2 pops before order 1
Queue a collection where the first item in is the first out the line at the counter
FIFO first in, first out: how a queue works Asha is served first
Pair[K, V] a generic type with two type parameters: a comparable key and any value Pair[string, int]{"chai", 10}
Methods on generic types methods whose receiver names the type parameters func (s *Stack[T]) Push(v T)
Receiver the value a method is called on, written before the method name (s *Stack[T])
Zero value the value a variable has when not set: 0, "", false, nil (episode 3) var n int is 0
Zero value of T var zero T: the zero value of whatever T turns out to be 0 for int, "" for string
Comma-ok returning a value plus a bool that says whether it was really there v, ok := First(xs)
Untyped constant a literal with no fixed type yet "chai", 42
%T fmt verb that prints a value's type main.Pair[string,int]
%q fmt verb that prints a string in quotes ""
%+v fmt verb that prints a struct with field names {Key:7 Val:true}
Compile error an error found while building, before the program runs []string does not satisfy comparable
# 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
Panic a run-time crash that stops the program comparing uncomparable type []string
Type safety the compiler stopping values of the wrong type Push(42) on Stack[string] is rejected
slices.Equal standard library function that compares two slices element by element instead of == on slices

Summary

  • Copy-paste per type duplicates code; []any fails because []string is not []any, and any throws the type away.
  • A type parameter in square brackets is a blank for a type ([T comparable]); a type argument fills it (int); a constraint (always an interface) says which types may.
  • any allows every type but promises almost nothing (no ==, no >); comparable promises == and !=; cmp.Ordered (preview) promises < and >.
  • Type inference usually works out T from the arguments, but not for a T used only in the result (Zero[int]()), and never for a generic type in a declaration (Stack[string]).
  • Instantiation substitutes the type arguments and then checks the constraints: Contains[int] is a plain func([]int, int) bool, and each instantiation is its own type.
  • Generic types like Stack[T] (LIFO) and Pair[K, V] have methods whose receiver names the type parameters; methods can't add their own.
  • var zero T gives the zero value of any T; return it with false in the comma-ok style.

Next episode: Generics part 2: constraints and type sets. Write your own constraints with type sets, unions and the ~ tilde, see how cmp.Ordered is built, and learn when not to use generics.