Skip to content

Come Back Later: Iterators and Typed Errors

The Course
•
50 min study

Come back to this page twice: the first two challenges after about a week, the last two after about a month.

What you can rebuild a few days later, without looking, is a far better measure of what you learned than what felt clear on the day. The effort of recalling is the point: each time you pull an idea back out of memory, it becomes easier to find the next time. The week challenges cover the ideas that are easiest to half-remember: an iterator that must respect yield, and an error that carries data through several layers of wrapping. The month challenges cover the hardest and most distinctive ideas of the course, from Days 4 and 5: a batch that applies all or nothing and recognises a retry, and a worker pool that keeps input order and stops when its context is cancelled.

How to use this page

Give yourself about fifteen minutes per exercise and do not scroll back through the course. If you get stuck, open only the first hint, then try again before opening the second. A different solution is fine if it passes the same checks.

After a week

A sorted, stoppable iterator

Before you start, recall the pieces: a type parameter constrained by cmp.Ordered, a second one for the values, iter.Seq2, and the rule about what an iterator must do when yield returns false.

Exercise

Your turn

Write SortedPairs[K cmp.Ordered, V any](m map[K]V) iter.Seq2[K, V], which yields a map's entries in key order. Use it to print the entries of a stock map, then to stop after the first entry whose value is 0, and check that the iterator really stops.

The output should be:

Text
drill=0 hat=0 lamp=7 tent=3 
first empty: drill after 1 entries
Your working space Go
package main

func main() {
	// Write SortedPairs, then range over it twice.
}
Hint 1: the idea

Sort the keys once when the iteration starts, then yield each key with its value, returning as soon as yield is false.

Hint 2: a first step

slices.Sorted(maps.Keys(m)) gives the keys. To check that it stops, count the calls to yield in a variable outside the loop body.

Worked solution
Run the solution Go
package main

import (
	"cmp"
	"fmt"
	"iter"
	"maps"
	"slices"
)

func SortedPairs[K cmp.Ordered, V any](m map[K]V) iter.Seq2[K, V] {
	return func(yield func(K, V) bool) {
		for _, k := range slices.Sorted(maps.Keys(m)) {
			if !yield(k, m[k]) {
				return
			}
		}
	}
}

func main() {
	stock := map[string]int{"tent": 3, "drill": 0, "lamp": 7, "hat": 0}
	for item, quantity := range SortedPairs(stock) {
		fmt.Printf("%s=%d ", item, quantity)
	}
	fmt.Println()
	visited := 0
	for item, quantity := range SortedPairs(stock) {
		visited++
		if quantity == 0 {
			fmt.Println("first empty:", item, "after", visited, "entries")
			break
		}
	}
}
Text
drill=0 hat=0 lamp=7 tent=3 
first empty: drill after 1 entries

The second loop stopped at drill, the first key in order, and the iterator returned without visiting the rest. A version that ignored yield's result would make Go panic with range function continued iteration.

Read data out of a wrapped error

Before you start, recall the pieces: an error type with fields and a pointer-receiver Error method, fmt.Errorf with %w, errors.Join, and the difference between errors.Is and errors.As.

Exercise

Your turn

Define LimitError with Item, Limit and Requested fields. Write checkOrder(lines map[string]int, limits map[string]int) error, which returns one *LimitError per item over its limit, in item order, joined together and wrapped with order:. Print the joined error on one line, with each newline replaced by ; . Use errors.As to read the first one's fields, and check that an order within every limit returns nil.

The output should be:

Text
order: drill: 3 requested, limit 1; tent: 6 requested, limit 4
first: drill over by 2
<nil>
Your working space Go
package main

func main() {
	// Define LimitError and checkOrder, then check two orders.
}
Hint 1: the idea

The error has three layers: the order: wrapper, the joined error, and each *LimitError. errors.As searches all of them and stops at the first match.

Hint 2: a first step

Range over slices.Sorted(maps.Keys(lines)) so the problems come out in item order, then return fmt.Errorf("order: %w", errors.Join(problems...)) only when there are problems.

Worked solution
Run the solution Go
package main

import (
	"errors"
	"fmt"
	"maps"
	"slices"
	"strings"
)

type LimitError struct {
	Item      string
	Limit     int
	Requested int
}

func (e *LimitError) Error() string {
	return fmt.Sprintf("%s: %d requested, limit %d", e.Item, e.Requested, e.Limit)
}

func checkOrder(lines, limits map[string]int) error {
	var problems []error
	for _, item := range slices.Sorted(maps.Keys(lines)) {
		if lines[item] > limits[item] {
			problems = append(problems, &LimitError{Item: item, Limit: limits[item], Requested: lines[item]})
		}
	}
	if len(problems) == 0 {
		return nil
	}
	return fmt.Errorf("order: %w", errors.Join(problems...))
}

func main() {
	limits := map[string]int{"tent": 4, "lamp": 2, "drill": 1}
	err := checkOrder(map[string]int{"tent": 6, "lamp": 2, "drill": 3}, limits)
	fmt.Println(strings.ReplaceAll(err.Error(), "\n", "; "))
	var limit *LimitError
	if errors.As(err, &limit) {
		fmt.Println("first:", limit.Item, "over by", limit.Requested-limit.Limit)
	}
	fmt.Println(checkOrder(map[string]int{"tent": 4, "drill": 1}, limits))
}
Text
order: drill: 3 requested, limit 1; tent: 6 requested, limit 4
first: drill over by 2
<nil>

lamp asked for exactly its limit and was accepted, and the second order sits on two limits at once. Checking len(problems) before wrapping matters: wrapping a nil joined error would return a non-nil error with the message order: %!w(<nil>).

After a month

Stage, commit and recognise a retry

Recall the Day 4 pattern before you start: normalise the request, recognise a known ID, change a copy of the state, check every line, and only then commit and record the ID.

Exercise

Your turn

A pantry tracks units of each ingredient. Write Apply(id string, changes []Change) (string, error) on the starter's Pantry, where a Change adds a positive or negative amount to one ingredient. A batch applies all its changes or none, and it is rejected with an error naming the ingredient if any count would go below zero. A known batch ID with the same changes in any order returns "replayed" and changes nothing, and a known ID with different changes returns errConflict. A rejected batch does not record its ID. Run the starter's four batches. The output should be:

Text
rejected: sugar would go below zero
map[flour:2 sugar:0]
applied <nil>
replayed <nil>
rejected: batch ID reused with different changes
map[flour:1 sugar:2]
Your working space Go
package main

import (
	"errors"
	"fmt"
)

type Change struct {
	Item  string
	Delta int
}

var errConflict = errors.New("batch ID reused with different changes")

type Pantry struct {
	stock   map[string]int
	batches map[string][]Change
}

func (p *Pantry) Apply(id string, changes []Change) (string, error) {
	return "", nil
}

func main() {
	p := &Pantry{stock: map[string]int{"flour": 2, "sugar": 0}, batches: map[string][]Change{}}
	try := func(id string, changes []Change) {
		result, err := p.Apply(id, changes)
		if err != nil {
			fmt.Println("rejected:", err)
			return
		}
		fmt.Println(result, err)
	}
	try("B1", []Change{{"sugar", -1}, {"flour", 5}})
	fmt.Println(p.stock)
	try("B2", []Change{{"sugar", 2}, {"flour", -1}})
	try("B2", []Change{{"flour", -1}, {"sugar", 2}})
	try("B2", []Change{{"flour", -2}})
	fmt.Println(p.stock)
}
Hint 1: the idea

Sort a copy of the changes before comparing or storing them, so the order a client sent doesn't matter. Apply every change to a clone of the stock, and assign the clone back only after the last change passed. After sorting, B1's flour change passes and is applied before its sugar change fails, which is exactly why it must be applied to a clone.

Hint 2: a first step

Start Apply with the normalisation: slices.Clone the changes and sort them by item with slices.SortFunc. Then look the ID up in p.batches, and compare a known batch's stored changes with slices.Equal.

Worked solution
Run the solution Go
package main

import (
	"cmp"
	"errors"
	"fmt"
	"maps"
	"slices"
)

type Change struct {
	Item  string
	Delta int
}

var errConflict = errors.New("batch ID reused with different changes")

type Pantry struct {
	stock   map[string]int
	batches map[string][]Change
}

func (p *Pantry) Apply(id string, changes []Change) (string, error) {
	normal := slices.Clone(changes)
	slices.SortFunc(normal, func(a, b Change) int { return cmp.Compare(a.Item, b.Item) })
	if known, ok := p.batches[id]; ok {
		if slices.Equal(known, normal) {
			return "replayed", nil
		}
		return "", errConflict
	}
	staged := maps.Clone(p.stock)
	for _, c := range normal {
		if staged[c.Item]+c.Delta < 0 {
			return "", fmt.Errorf("%s would go below zero", c.Item)
		}
		staged[c.Item] += c.Delta
	}
	p.stock = staged
	p.batches[id] = normal
	return "applied", nil
}

func main() {
	p := &Pantry{stock: map[string]int{"flour": 2, "sugar": 0}, batches: map[string][]Change{}}
	try := func(id string, changes []Change) {
		result, err := p.Apply(id, changes)
		if err != nil {
			fmt.Println("rejected:", err)
			return
		}
		fmt.Println(result, err)
	}
	try("B1", []Change{{"sugar", -1}, {"flour", 5}})
	fmt.Println(p.stock)
	try("B2", []Change{{"sugar", 2}, {"flour", -1}})
	try("B2", []Change{{"flour", -1}, {"sugar", 2}})
	try("B2", []Change{{"flour", -2}})
	fmt.Println(p.stock)
}
Text
rejected: sugar would go below zero
map[flour:2 sugar:0]
applied <nil>
replayed <nil>
rejected: batch ID reused with different changes
map[flour:1 sugar:2]

Replace maps.Clone(p.stock) with p.stock and run it: B1 is still rejected, but the stock now shows flour:7, because the flour change was written before the sugar check failed. Recording the ID only after the commit lets a rejected batch be fixed and sent again under the same ID. slices.Equal works on []Change because Change is a comparable struct.

A pool that keeps order and stops on cancel

Recall the Day 5 pieces first: a jobs channel of indexes, a fixed number of workers, one result slot per index, a select that stops sending when the context is done, and ctx.Err() checked after the workers finish.

Exercise

Your turn

Write countWords(ctx context.Context, docs []string, workers int) ([]int, error), which counts the words in each document on a pool of workers goroutines and returns the counts in input order. If the context is cancelled, it stops handing out work and returns nil and the context's error. It must work when there are more workers than documents, and for no documents at all. The starter calls it three times. The output should be:

Text
[2 0 3] <nil>
[] <nil>
[] context canceled
Your working space Go
package main

import (
	"context"
	"fmt"
)

func countWords(ctx context.Context, docs []string, workers int) ([]int, error) {
	return nil, nil
}

func main() {
	docs := []string{"pack tent", "", "buy lamp oil"}
	fmt.Println(countWords(context.Background(), docs, 8))
	fmt.Println(countWords(context.Background(), nil, 2))
	ctx, cancel := context.WithCancel(context.Background())
	cancel()
	fmt.Println(countWords(ctx, docs, 2))
}
Hint 1: the idea

Each worker writes only its own index in the result slice, so no lock is needed and the order can't depend on scheduling. Sending each index through a select with a ctx.Done() case lets the sender stop early. Whatever happened meanwhile, ctx.Err() after wg.Wait() decides the answer.

Hint 2: a first step

Write it with no cancellation first: results := make([]int, len(docs)), an unbuffered jobs channel, workers that range over jobs and use len(strings.Fields(...)), a loop that sends every index, then close(jobs) and wg.Wait(). The first two lines of output should be right. Then add the select.

Worked solution
Run the solution Go
package main

import (
	"context"
	"fmt"
	"strings"
	"sync"
)

func countWords(ctx context.Context, docs []string, workers int) ([]int, error) {
	workers = max(1, min(workers, len(docs)))
	results := make([]int, len(docs))
	jobs := make(chan int)
	var wg sync.WaitGroup
	for range workers {
		wg.Add(1)
		go func() {
			defer wg.Done()
			for i := range jobs {
				results[i] = len(strings.Fields(docs[i]))
			}
		}()
	}
send:
	for i := range docs {
		select {
		case jobs <- i:
		case <-ctx.Done():
			break send
		}
	}
	close(jobs)
	wg.Wait()
	if err := ctx.Err(); err != nil {
		return nil, err
	}
	return results, nil
}

func main() {
	docs := []string{"pack tent", "", "buy lamp oil"}
	fmt.Println(countWords(context.Background(), docs, 8))
	fmt.Println(countWords(context.Background(), nil, 2))
	ctx, cancel := context.WithCancel(context.Background())
	cancel()
	fmt.Println(countWords(ctx, docs, 2))
}
Text
[2 0 3] <nil>
[] <nil>
[] context canceled

With a cancelled context, select may still send an index or two, because both of its cases can be ready and Go picks one at random. That is why the answer comes from ctx.Err() after the workers stop, not from how many jobs were sent, and the output is the same on every run. Clamping workers avoids starting eight goroutines for three documents, and the max(1, ...) keeps one worker for an empty list so the code needs no special case. break send leaves the for loop, not just the select.

Was this article helpful?

Your response is saved on this device.