Skip to content

Use the Standard Iterators

The Course
•
24 min study

The maps and slices packages produce and consume iterators, so you rarely write the plumbing yourself. The most useful pairing for reports is this: maps.Keys(m) yields a map's keys in no particular order, and slices.Sorted collects any iterator of ordered values into a new, sorted slice. Together they replace the five lines of "make a slice, append every key, sort it" from the intermediate course.

A few more you will use this week: slices.Collect gathers any iterator into a slice without sorting, maps.Values yields a map's values, slices.All yields index and value pairs, and slices.Values yields a slice's elements.

Predict and run

maps.Keys alone has no order. What does each line print?

Predict, then run Go
package main

import (
	"fmt"
	"maps"
	"slices"
)

func main() {
	stock := map[string]int{"tent": 3, "drill": 0, "lamp": 7}
	names := slices.Sorted(maps.Keys(stock))
	fmt.Println(names)
	for _, name := range names {
		fmt.Printf("%s=%d ", name, stock[name])
	}
	fmt.Println()
	total := 0
	for q := range maps.Values(stock) {
		total += q
	}
	fmt.Println("Units:", total)
}
Check your prediction
Text
[drill lamp tent]
drill=0 lamp=7 tent=3 
Units: 10

The total does not depend on order, so ranging over maps.Values directly is fine. The listing does, so it goes through the sorted names. Print slices.Collect(maps.Keys(stock)) a few times in a loop. On some runs the order changes, which is exactly why reports never use it.

Return an iterator from a method

A type can offer an iterator over its contents instead of exposing its map. The ledger's Items method below yields each item and quantity in name order. Callers can range over it, stop early, or collect it, and the ledger is free to change how it stores stock later without breaking them.

A method that yields sorted pairs Go
package main

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

type Ledger struct {
	stock map[string]int
}

func (l *Ledger) Items() iter.Seq2[string, int] {
	return func(yield func(string, int) bool) {
		for _, item := range slices.Sorted(maps.Keys(l.stock)) {
			if !yield(item, l.stock[item]) {
				return
			}
		}
	}
}

func main() {
	l := &Ledger{stock: map[string]int{"tent": 3, "drill": 0, "lamp": 7}}
	for item, quantity := range l.Items() {
		if quantity == 0 {
			fmt.Println("Out of stock:", item)
		}
	}
	for item := range l.Items() {
		fmt.Println("First item:", item)
		break
	}
}
Text
Out of stock: drill
First item: drill

The second loop uses only the first of the two values and breaks at once. range over an iter.Seq2 may name one variable or both, just as with a map.

Collect at the edge

Iterators shine in the middle of a computation and slices at its edges. A function that returns data to callers, or holds it for later, usually returns a slice: callers can index it, take its length and range over it twice. Keep iterators for walking data you already have, and for sources you do not want to load all at once. slices.Collect is the bridge between the two.

Sorted keys, every time

Whenever output depends on a map, write slices.Sorted(maps.Keys(m)) before you print anything. This course's checks compare exact output, and an unsorted map is the most common reason a Go program's output changes from run to run.

Practice

Exercise

Your turn

Write lowStock(stock map[string]int, limit int) []string, which returns the names of items with at most limit units, sorted by name. Build it from slices.Sorted, maps.Keys and a loop. Check limit 1 and limit 0 on tent 3, drill 0, lamp 1, hat 0, and print [] when nothing qualifies at a limit below every quantity.

The output should be:

Text
[drill hat lamp]
[drill hat]
[]
Your working space Go
package main

func main() {
	stock := map[string]int{"tent": 3, "drill": 0, "lamp": 1, "hat": 0}
	_ = stock
	// Write lowStock, then check three limits.
}
Hint 1: the idea

Sort the names first, then keep the low ones in that order. The result is sorted without a second sort.

Hint 2: a first step

Range over slices.Sorted(maps.Keys(stock)) and append each name whose quantity is <= limit. Start the result with []string{} rather than leaving it nil. fmt.Println prints both as [], so the difference doesn't show here. It shows when a caller encodes the result as JSON, where a nil slice becomes null and an empty one [], or checks result == nil.

Worked solution
Run the solution Go
package main

import (
	"fmt"
	"maps"
	"slices"
)

func lowStock(stock map[string]int, limit int) []string {
	low := []string{}
	for _, item := range slices.Sorted(maps.Keys(stock)) {
		if stock[item] <= limit {
			low = append(low, item)
		}
	}
	return low
}

func main() {
	stock := map[string]int{"tent": 3, "drill": 0, "lamp": 1, "hat": 0}
	fmt.Println(lowStock(stock, 1))
	fmt.Println(lowStock(stock, 0))
	fmt.Println(lowStock(stock, -1))
}
Text
[drill hat lamp]
[drill hat]
[]

Limit 1 includes lamp, which has exactly one unit, and limit 0 excludes it, so the <= is checked from both sides. On Day 7 you will add the same kind of report to the project.

Was this article helpful?

Your response is saved on this device.