Generic types, inference and the standard library

A type can have parameters as well as a function: Stack[T] is one type declaration that the compiler instantiates per element type, with the same body and no boxing. Inference and the standard library are what make generics pleasant to use: a call site rarely writes the type argument, and slices, maps and cmp already hold the generic code a program would otherwise write. The previous lesson introduced the syntax; this one uses it the way the standard library does.

A generic type

The type parameter belongs to the type, and the receiver repeats it: func (s *Stack[T]) Push(v T) is a method of every instantiation. The zero-value pattern gives Pop a value to return when the stack is empty, because a type parameter has no nil that fits every T. A pointer receiver is used here because Push and Pop change the slice header.

package main import "fmt" 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 } last := len(s.items) - 1 v := s.items[last] s.items = s.items[:last] return v, true } func main() { var ints Stack[int] ints.Push(1) ints.Push(2) v, _ := ints.Pop() fmt.Println(v, len(ints.items)) var words Stack[string] words.Push("go") w, ok := words.Pop() fmt.Println(w, ok) _, ok = words.Pop() fmt.Println(ok) }

go run stack.go

2 1
go true
false

The same declaration served ints and strings. Each instantiation has its own methods and its own representation, so Stack[int] and Stack[string] are different types that do not convert into each other. That is the price of the type safety: no reflection, no interface boxing, and a compile error when the element types are mixed.

Inference and cmp

The call site usually writes nothing in brackets: the compiler infers T from the arguments. cmp.Compare is the standard comparison for any ordered type and returns -1, 0 or 1, which is exactly what slices.SortFunc wants. slices.IndexFunc and slices.Contains replace the hand-written loops of the pre-generics era.

package main import ( "cmp" "fmt" "slices" ) type person struct { Name string Age int } func main() { people := []person{{"ada", 36}, {"grace", 45}, {"linus", 28}} slices.SortFunc(people, func(a, b person) int { return cmp.Compare(a.Age, b.Age) }) fmt.Println(people) idx := slices.IndexFunc(people, func(p person) bool { return p.Name == "grace" }) fmt.Println("grace at", idx) fmt.Println(slices.Contains(people, person{"linus", 28})) }

go run sorts.go

[{linus 28} {ada 36} {grace 45}]
grace at 2
true

The sort was stable only in the sense that equal ages would keep an arbitrary order; SortStableFunc is the version that keeps the input order for equal keys. The slice was sorted in place, which the name slices.SortFunc does not hide, and the original order is gone unless a copy is made first.

maps and slices together

maps.Keys returns an iterator, not a slice, and slices.Sorted collects and sorts it in one call. That pair replaced the three-step recipe of collecting keys, sorting them and ranging over the result. maps.Clone copies the header and the entries into a new table, so the copy can be changed without touching the original, and maps.Equal compares two maps entry by entry.

package main import ( "fmt" "maps" "slices" ) func main() { ages := map[string]int{"ada": 36, "grace": 45, "linus": 28} names := slices.Sorted(maps.Keys(ages)) fmt.Println(names) copyOf := maps.Clone(ages) copyOf["ada"] = 37 fmt.Println("original:", ages["ada"], "copy:", copyOf["ada"]) fmt.Println("equal:", maps.Equal(ages, copyOf)) }

go run maps.go

[ada grace linus]
original: 36 copy: 37
equal: false

The clone kept 36 while the original's copy of the entry went to 37, and Equal reported false, which is how a test asserts that a function did not mutate its input. None of these functions existed before Go 1.21; a course page written earlier would have shown the sort of a []string built by hand.

A method cannot have type parameters

Methods may use the type parameters of their receiver, but they may not declare new ones. The reason is that a method is selected by name and receiver type, and a method with its own parameter would need an instantiation rule the language does not have. The workaround is a generic function that takes the value as an argument, or a generic helper type.

package main type Stack[T any] struct { items []T } func (s Stack[T]) Map[U any](f func(T) U) Stack[U] { var out Stack[U] return out } func main() { var s Stack[int] _ = s }

go build -o badmethod badmethod.go

# command-line-arguments
./badmethod.go:7:22: syntax error: method must have no type parameters

The parser reports it as a syntax error because the bracket is not allowed in the grammar at all. Write func Map[T, U any](s Stack[T], f func(T) U) Stack[U] instead, and the same operation works on every instantiation.

Exercises

  1. Add a Len method and a Peek to Stack and use them with a Stack[float64]. Which receiver kind does Peek need?
  2. Sort a slice of structs by two keys with slices.SortFunc and cmp.Compare. What does the comparison return when the first keys are equal?
  3. Replace a hand-written key sort with slices.Sorted(maps.Keys(m)) and count the lines that disappear. What type does maps.Keys return?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does Stack[int] have that Stack[string] does not?

    Answer

    Nothing in the declaration, but the two are distinct instantiated types

    One declaration, two instantiations: same methods, different element types.

  2. What does this program print? package main import "fmt" 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 } last := len(s.items) - 1 v := s.items[last] s.items = s.items[:last] return v, true } func main() { var ints Stack[int] ints.Push(1) ints.Push(2) v, _ := ints.Pop() fmt.Println(v, len(ints.items)) var words Stack[string] words.Push("go") w, ok := words.Pop() fmt.Println(w, ok) _, ok = words.Pop() fmt.Println(ok) }

    Answer

    2 1 / go true / false

    Pop returned the last pushed value and left one item; the second Pop on an empty stack reported false.

  3. What does cmp.Compare return?

    Answer

    -1, 0 or 1

    The three-way result is what SortFunc and the other comparison-driven functions expect.

  4. What does the second line of this program print? package main import ( "cmp" "fmt" "slices" ) type person struct { Name string Age int } func main() { people := []person{{"ada", 36}, {"grace", 45}, {"linus", 28}} slices.SortFunc(people, func(a, b person) int { return cmp.Compare(a.Age, b.Age) }) fmt.Println(people) idx := slices.IndexFunc(people, func(p person) bool { return p.Name == "grace" }) fmt.Println("grace at", idx) fmt.Println(slices.Contains(people, person{"linus", 28})) }

    Answer

    [{linus 28} {ada 36} {grace 45}] / grace at 2 / true

    The people were sorted by age, so grace, 45, is the second element at index 1.

  5. What does maps.Keys return?

    Answer

    An iterator over the keys

    It returns an iterator, which slices.Sorted or slices.Collect turns into a slice.

  6. What does the first line of this program print? package main import ( "fmt" "maps" "slices" ) func main() { ages := map[string]int{"ada": 36, "grace": 45, "linus": 28} names := slices.Sorted(maps.Keys(ages)) fmt.Println(names) copyOf := maps.Clone(ages) copyOf["ada"] = 37 fmt.Println("original:", ages["ada"], "copy:", copyOf["ada"]) fmt.Println("equal:", maps.Equal(ages, copyOf)) }

    Answer

    [ada grace linus] / original: 36 copy: 37 / equal: false

    Sorted keys come out in alphabetical order regardless of the map's iteration order.

  7. Why can a method not declare its own type parameters?

    Answer

    Method selection is by name and receiver type, and the grammar has no rule for it

    A generic function that takes the value is the supported form.

  8. What does the compiler say about this program? package main type Stack[T any] struct { items []T } func (s Stack[T]) Map[U any](f func(T) U) Stack[U] { var out Stack[U] return out } func main() { var s Stack[int] _ = s }

    Answer

    error: method must have no type parameters

    The bracket after the method name is not in the grammar; the parser reports it first.

  9. What does maps.Clone give the caller?

    Answer

    A new map with the same entries that can be changed independently

    Clone allocates a new table, so writes to the copy do not reach the original.

  10. What does the last line of this program print? package main import ( "fmt" "maps" "slices" ) func main() { ages := map[string]int{"ada": 36, "grace": 45, "linus": 28} names := slices.Sorted(maps.Keys(ages)) fmt.Println(names) copyOf := maps.Clone(ages) copyOf["ada"] = 37 fmt.Println("original:", ages["ada"], "copy:", copyOf["ada"]) fmt.Println("equal:", maps.Equal(ages, copyOf)) }

    Answer

    [ada grace linus] / original: 36 copy: 37 / equal: false

    The clone was changed after copying, so the two maps are no longer equal.

The code on this page was run with go 1.26.10 on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev