Writing it once
For its first ten years Go had no way to write a function that worked for "a slice of anything". You could write SumInts and SumFloats separately, or accept interface{} and give up type checking. Generic data structures (a set, a stack, a cache) had to be written once per element type or built on interface{} with type assertions everywhere. This was the most requested feature in Go's history, and the hardest to add without spoiling the language's simplicity and fast compilation.
Generics arrived in Go 1.18 (2022), after more than a decade of design work led by Ian Lance Taylor and Robert Griesemer. Functions and types can take type parameters, written in square brackets, constrained by interfaces that describe which types are allowed. The slices, maps and cmp packages you used in lesson 4 are built on them.
Two later additions completed the picture. Go 1.23 introduced range-over-func iterators: a function with a particular shape can be used directly in a for range loop, which gives every collection, generator and stream one standard way to be iterated. And Go 1.27, the version this course uses, allows methods with their own type parameters, removing the most common complaint about Go's first generics design. This lesson covers all three, and also when not to reach for them.
Type parameters and constraints
Definition— type parameter and constraint
A type parameter list in square brackets, func Map[T, U any](...), declares placeholder types. Each has a constraint, an interface that the type argument must satisfy. Besides methods, a constraint interface may list a type set: int | float64 allows exactly those types, and ~int allows int and every type whose underlying type is int. The predeclared any allows every type, and comparable allows every type that supports ==.
package main
import (
"cmp"
"fmt"
"strings"
)
// Map applies f to every element. T and U are type parameters.
func Map[T, U any](items []T, f func(T) U) []U {
out := make([]U, 0, len(items))
for _, it := range items {
out = append(out, f(it))
}
return out
}
func Filter[T any](items []T, keep func(T) bool) []T {
var out []T
for _, it := range items {
if keep(it) {
out = append(out, it)
}
}
return out
}
// cmp.Ordered permits every type that supports < and >.
func Largest[T cmp.Ordered](items []T) (T, bool) {
var best T
if len(items) == 0 {
return best, false
}
best = items[0]
for _, it := range items[1:] {
if it > best {
best = it
}
}
return best, true
}
// A custom constraint: a type set. ~int means int or any type whose underlying type is int.
type Number interface {
~int | ~int64 | ~float64
}
func Sum[T Number](items []T) T {
var total T
for _, it := range items {
total += it
}
return total
}
// comparable permits types usable with == (and as map keys).
func CountDistinct[T comparable](items []T) int {
seen := make(map[T]bool)
for _, it := range items {
seen[it] = true
}
return len(seen)
}
type Cents int // underlying type int, so it satisfies ~int
func main() {
words := []string{"jollof", "pho", "arepa", "borscht", "pho"}
lengths := Map(words, func(s string) int { return len(s) }) // T=string, U=int inferred
fmt.Println(lengths)
fmt.Println(Filter(words, func(s string) bool { return strings.ContainsRune(s, 'o') }))
w, _ := Largest(words)
n, _ := Largest(lengths)
_, ok := Largest([]float64{})
fmt.Println(w, n, ok)
fmt.Println(Sum([]float64{1.5, 2.25}), Sum([]Cents{150, 275}))
fmt.Println(CountDistinct(words), CountDistinct([]int{1, 1, 2}))
fmt.Println(Map[int, string](lengths, func(n int) string { return strings.Repeat("*", n) })[1])
}[6 3 5 7 3]
[jollof pho borscht pho]
pho 7 false
3.75 425
4 2
***What's going on:
- Type inference fills in the type arguments from the ordinary arguments, so
Map(words, ...)needs no[string, int]. You can still write them explicitly, as the last line does; that's necessary only when inference has nothing to go on, such as a function whose type parameter appears only in its result. anyletsMapandFilteraccept every type, but then the body can do only what works for every type: assign, pass along, put in slices. To use<,Largestasks forcmp.Ordered, the standard constraint for integers, floats and strings; strings compare alphabetically, so "pho" is the "largest" word. Note how the generic code returns the zero value ofT(var best T) when the slice is empty, together with afalse.Numberis a custom constraint written as a type set. The tildes matter:Sum([]Cents{150, 275})compiles only because~intincludes types whose underlying type isint. Without the tilde, the compiler reports "Cents does not satisfy Number (possibly missing ~ for int in Number)".comparableis what map keys need, soCountDistinctcan build amap[T]bool.
Generic functions are type-checked once, against their constraints, not separately for each use. A body that tries something the constraint doesn't allow (calling .Len() on an any, say) is an error in the generic function itself, with a clear message, rather than an error deep inside some caller.
Generic types and generic methods
package main
import (
"fmt"
"strings"
)
// Stack is a generic type: one definition, a separate concrete type for each T.
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 (s *Stack[T]) Len() int { return len(s.items) }
// A generic method (Go 1.27+): Convert has its own type parameter U,
// in addition to the type's parameter T.
func (s *Stack[T]) Convert[U any](f func(T) U) *Stack[U] {
out := &Stack[U]{items: make([]U, 0, len(s.items))}
for _, v := range s.items {
out.items = append(out.items, f(v))
}
return out
}
// Balanced checks brackets with a Stack[rune].
func Balanced(s string) bool {
pairs := map[rune]rune{')': '(', ']': '[', '}': '{'}
var st Stack[rune] // the zero value is an empty, usable stack
for _, r := range s {
switch r {
case '(', '[', '{':
st.Push(r)
case ')', ']', '}':
top, ok := st.Pop()
if !ok || top != pairs[r] {
return false
}
}
}
return st.Len() == 0
}
func main() {
for _, expr := range []string{"f(a[1], {b: 2})", "(]", "((x)"} {
fmt.Printf("%-16q balanced: %v\n", expr, Balanced(expr))
}
var plates Stack[string]
plates.Push("blue")
plates.Push("white")
upper := plates.Convert(strings.ToUpper) // U inferred as string
sizes := plates.Convert(func(s string) int { return len(s) })
top, _ := upper.Pop()
fmt.Println(top, sizes.items, plates.Len())
}"f(a[1], {b: 2})" balanced: true
"(]" balanced: false
"((x)" balanced: false
WHITE [4 5] 2Stack[T]is defined once and used asStack[rune]for bracket matching andStack[string]for plates. Methods on a generic type repeat the type parameter in the receiver,(s *Stack[T]), and can useTthroughout. The zero value of aStackis an empty stack, ready to use, in good Go style.Popreturns(T, bool): the usual comma-ok shape. A generic function can't returnnilfor everyT(anintcan't be nil), so it returns the zero value and a flag.Convertis a generic method, new in Go 1.27: besides the type's ownT, it declares its own type parameterU, so aStack[string]can become aStack[int]. Before Go 1.27 this had to be a top-level function,Convert(s, f), which reads less naturally in a chain. Generic methods have one restriction worth knowing: they can't be used to satisfy an interface, because an interface method can't have type parameters.Balancedis a classic use of a stack: push opening brackets, and on each closing bracket pop and check that it matches. The%-16qverb left-aligns the quoted string in a 16-character column.
Iterators: range over functions
Definition— iterator
An iterator in Go is a function that takes a yield callback and calls it once for each value it produces, stopping early if yield returns false. The standard names are iter.Seq[V], a func(yield func(V) bool), and iter.Seq2[K, V], a func(yield func(K, V) bool) for pairs. Since Go 1.23 such functions can be used directly as the range expression of a for loop.
package main
import (
"fmt"
"iter"
"maps"
"slices"
"strings"
)
// Primes yields prime numbers forever; the caller decides when to stop.
func Primes() iter.Seq[int] {
return func(yield func(int) bool) {
for n := 2; ; n++ {
isPrime := true
for d := 2; d*d <= n; d++ {
if n%d == 0 {
isPrime = false
break
}
}
if isPrime && !yield(n) { // yield returns false when the loop breaks
return
}
}
}
}
// Indexed yields pairs, like range over a slice does: an iter.Seq2.
func Words(text string) iter.Seq2[int, string] {
return func(yield func(int, string) bool) {
i := 0
for w := range strings.FieldsSeq(text) {
if !yield(i, strings.ToLower(w)) {
return
}
i++
}
}
}
// Take is an iterator adaptor: it wraps another iterator.
func Take[T any](seq iter.Seq[T], n int) iter.Seq[T] {
return func(yield func(T) bool) {
if n <= 0 {
return
}
count := 0
for v := range seq {
if !yield(v) {
return
}
count++
if count == n {
return
}
}
}
}
func main() {
for p := range Primes() {
if p > 30 {
break
}
fmt.Print(p, " ")
}
fmt.Println("...")
fmt.Println(slices.Collect(Take(Primes(), 8)))
var first []string
for i, w := range Words("Ubuntu means I am because WE are") {
if i >= 4 {
break
}
first = append(first, fmt.Sprintf("%d=%s", i, w))
}
fmt.Println(strings.Join(first, " "))
// The standard library speaks the same protocol.
ages := map[string]int{"Ana": 31, "Bo": 25, "Cy": 40}
fmt.Println(slices.Sorted(maps.Keys(ages)))
for i, v := range slices.Backward([]string{"a", "b", "c"}) {
fmt.Println(i, v)
}
}2 3 5 7 11 13 17 19 23 29 ...
[2 3 5 7 11 13 17 19]
0=ubuntu 1=means 2=i 3=am
[Ana Bo Cy]
2 c
1 b
0 aThe protocol is simple once you see it from both sides. Primes is an infinite loop that calls yield(n) for each prime. When the for range loop body runs break, the compiler arranges for that yield call to return false, and the iterator must then stop (return). Forgetting to check yield's result is a bug: the runtime panics if an iterator keeps yielding after the loop has ended.
Iterators compose. Take wraps any iter.Seq and stops it after n values, so slices.Collect(Take(Primes(), 8)) turns an infinite sequence into a slice of eight. Words is an iter.Seq2 that yields index-word pairs, built on strings.FieldsSeq (Go 1.24), one of several standard functions that return iterators instead of allocating a whole slice. The standard library uses the same protocol everywhere: maps.Keys and maps.Values, slices.All, slices.Values and slices.Backward, strings.Lines and strings.SplitSeq, and functions that consume iterators such as slices.Collect and slices.Sorted.
Iterators are lazy: nothing is computed until a loop asks for the next value, so they can describe infinite sequences, read huge files line by line without loading them, or stop a database scan early. For the rarer case where you need to pull values one at a time (to merge two sequences, say), iter.Pull converts a push-style iterator into a next() function.
Should a function return a slice or an iterator? Return a slice when the result is small, when callers will index into it or ask for its length, or when it must be a stable snapshot that won't change if the underlying data does. Return an iterator when the sequence may be large or unbounded, when producing each element costs something and callers often stop early, or when the data lives in a structure (a tree, a map, a file) that a slice would have to copy. Many APIs offer both: a method returning an iterator, and callers who want a slice use slices.Collect. Either way, document whether the order is meaningful, because callers will otherwise assume it is.
Worked example: a generic set with an iterator
Generic types and iterators are at their best together. Go has no built-in set, so here is a small one, the kind of utility many codebases carry:
type Set[T comparable] struct {
m map[T]struct{}
}
func (s *Set[T]) Add(vs ...T) {
if s.m == nil {
s.m = make(map[T]struct{})
}
for _, v := range vs {
s.m[v] = struct{}{}
}
}
func (s *Set[T]) Has(v T) bool { _, ok := s.m[v]; return ok }
func (s *Set[T]) Len() int { return len(s.m) }
// All returns an iterator over the members, in no particular order.
func (s *Set[T]) All() iter.Seq[T] {
return func(yield func(T) bool) {
for v := range s.m {
if !yield(v) {
return
}
}
}
}Several decisions here are typical of good Go. The constraint is comparable, exactly what map keys require, and no more. The values are struct{}, which takes no memory. The zero value is usable: Add creates the map on first use, so var visited Set[string] needs no constructor. And instead of returning a slice of members, which would allocate and copy, All returns an iterator, so callers can write for city := range visited.All() or collect a sorted list with slices.Sorted(visited.All()). Iteration order follows the map's, which is random, and the comment says so.
A natural extension is a generic method such as func (s *Set[T]) Map[U comparable](f func(T) U) *Set[U], which Go 1.27 now allows on the type itself.
How Go got generics
Go's designers said from the start that generics might come later, once they found a design that fitted the language. It took twelve years. Several proposals between 2010 and 2016 were judged too complex. A 2018 draft introduced "contracts", a new kind of declaration for constraints; feedback was that it added a second, unfamiliar concept, and in 2020 the design was reworked to express constraints as ordinary interfaces, extended with type sets. In parallel, a team of programming-language researchers and Go team members, including Philip Wadler, formalised a core of the design in a paper called "Featherweight Go" (2020) to check that it was sound. The result shipped in Go 1.18 in March 2022. Iterators followed in Go 1.23 (2024), generic type aliases in Go 1.24 (2025), and generic methods in Go 1.27 (2026), each after its own long public discussion.
When to use generics
The Go team's guidance, and the habit of experienced Go programmers, is to write ordinary code first and introduce type parameters when you find yourself writing the same code for different types. Some concrete rules of thumb:
- Good uses: functions over slices, maps and channels of any element type (
Map,Filter,Keys,Chunk); general-purpose data structures (sets, stacks, ordered maps, caches, priority queues); and utilities with an obvious type relationship between inputs and outputs (Max,Clamp,Ptr). - Prefer an interface when the code calls methods and doesn't care about the concrete type: a function that writes to an
io.Writergains nothing from beingfunc Write[W io.Writer](w W); a plainio.Writerparameter is simpler and just as fast in practice. - Prefer a concrete type when there is only one type in play. Generic code that is used with a single type is harder to read for no benefit.
- Don't build class hierarchies out of constraints. Constraints describe what operations a function needs, not taxonomies of your domain.
Readability is the deciding factor, as always in Go. A short generic helper used in thirty places is a win; a generic framework that makes every signature carry three type parameters is not.
On performance: Go compiles generic code with a hybrid strategy (one compiled body per group of types that share a memory layout, with a small dictionary describing the type), which keeps binaries small and builds fast. Generic code is usually as fast as hand-written code, occasionally slightly slower when it calls methods through a type parameter. As ever, measure before optimising.
Common misconceptions
Misconception
"any in a type parameter list means the code works like interface{}." A type parameter constrained by any is still one specific type at each call: Map[string, int] has string elements, checked at compile time, with no boxing into interfaces and no type assertions.
Misconception
"int | float64 accepts my type Celsius float64." Only with a tilde. float64 in a type set means exactly float64; ~float64 means every type whose underlying type is float64. The compiler's error message even suggests the missing ~.
Misconception
"Iterators are like Python generators, running in a separate thread or coroutine." A Go iterator is an ordinary function call: the loop body is turned into the yield callback, and everything runs on the same goroutine with no extra scheduling. That is why they are cheap enough to use everywhere.
Misconception
"Generic methods let a type satisfy a generic interface method." Interface methods can't have type parameters, so generic methods are for convenience and readability, not for interface satisfaction.
Exercises
1. Generics and iterators
Warm-upComputationalWhat does fmt.Println(slices.Collect(Countdown(4))) print?
func Countdown(n int) iter.Seq[int] {
return func(yield func(int) bool) {
for i := n; i > 0; i-- {
if !yield(i) {
return
}
}
}
}
2. Generics and iterators
CoreComputationalUsing Countdown from the previous exercise, what is total after this loop?
total := 0
for v := range Countdown(10) {
if v < 7 {
break
}
total += v
}
3. Generics and iterators
CoreComputationalWith type Number interface{ int | float64 } and type Cents int, why does Sum([]Cents{1, 2}) fail to compile?
4. Generics and iterators
CoreHumanYou are writing func Dedupe[T ???](items []T) []T, which uses a map[T]bool to drop repeated items. What is the least restrictive constraint that compiles?
5. Generics and iterators
CoreComputationalWhat does this print?
type Pair[K comparable, V any] struct {
Key K
Val V
}
func Swap[A comparable, B any](p Pair[A, B]) (B, A) { return p.Val, p.Key }
func main() {
v, k := Swap(Pair[string, int]{"x", 1})
fmt.Println(v, k)
}
6. Generics and iterators
StretchComputationalAn iterator calls yield(i) in a loop but ignores its result. What happens when a caller breaks out of a for range over it?