Skip to content

Write an Iterator

The Course
•
24 min study

A function that returns a slice must build the whole slice before the caller sees anything. That is fine for ten values and wasteful for a million, and impossible for a sequence with no end. An iterator hands out values one at a time, on demand. Since Go 1.23, a for ... range loop can range over a function, which is how Go spells an iterator.

The iterator types live in the iter package. iter.Seq[V] is func(yield func(V) bool): a function that receives a callback, yield, and calls it once per value. Each call to yield runs one pass of the loop body. yield returns false when the loop has stopped, for example because of break, and the iterator must then return without calling it again.

Predict and run

countdown prints a note each time it produces a value. The loop stops early. Which lines appear?

Predict, then run Go
package main

import (
	"fmt"
	"iter"
)

func countdown(from int) iter.Seq[int] {
	return func(yield func(int) bool) {
		for n := from; n >= 1; n-- {
			fmt.Println("producing", n)
			if !yield(n) {
				fmt.Println("stopped early")
				return
			}
		}
	}
}

func main() {
	for n := range countdown(4) {
		fmt.Println("got", n)
		if n == 3 {
			break
		}
	}
}
Check your prediction
Text
producing 4
got 4
producing 3
got 3
stopped early

The lines alternate because producing and consuming take turns: yield(4) runs the loop body with 4, then returns to the iterator. countdown never produced 2 or 1, because the break made yield return false. Remove the break and predict the output again.

yield returning false is a promise to keep

If an iterator keeps calling yield after it returned false, Go stops the program with a panic: range function continued iteration after function for loop body returned false. Every iterator therefore checks the result of yield and returns as soon as it is false. The one-line form if !yield(v) { return } is the idiom you will see everywhere.

Pairs with iter.Seq2

iter.Seq2[K, V] yields two values per step, like ranging over a map or a slice with an index. The project reads input through one of these: it yields each line number with that line's text, so the parser can report errors by line without counting them itself. This version also skips blank lines, which is exactly the kind of logic an iterator can hide from its callers.

Yield line numbers with lines Go
package main

import (
	"fmt"
	"iter"
	"strings"
)

func nonBlank(lines []string) iter.Seq2[int, string] {
	return func(yield func(int, string) bool) {
		for i, line := range lines {
			if strings.TrimSpace(line) == "" {
				continue
			}
			if !yield(i+1, line) {
				return
			}
		}
	}
}

func main() {
	input := []string{"stock tent 5", "", "order A1 tent:2", "  ", "report"}
	for number, line := range nonBlank(input) {
		fmt.Printf("%d: %s\n", number, line)
	}
}
Text
1: stock tent 5
3: order A1 tent:2
5: report

The numbers keep their gaps, because the iterator numbers the original lines before skipping. Moving the continue after a counter that only counts non-blank lines would renumber them, and every error message would then point at the wrong line.

Iterators are ordinary functions

Nothing about countdown is special syntax except the range. You could call it directly: countdown(2)(func(n int) bool { fmt.Println(n); return true }). The range form just writes that callback for you, and turns break, continue and return inside the loop into the right yield results.

Practice

Exercise

Your turn

Write Filtered[T any](values []T, keep func(T) bool) iter.Seq[T]. It must not build a new slice: it yields each value for which keep is true, as the loop asks for it. Use it to print the first two quantities above 10 from 4, 12, 7, 30, 18, and stop the loop after the second.

The output should be:

Text
Large: 12
Large: 30
Your working space Go
package main

func main() {
	// Write Filtered, then range over it and stop after two values.
}
Hint 1: the idea

Combine Day 1 and today: the type parameter and the keep function come from generics, and the returned function calls yield instead of appending.

Hint 2: a first step

Start from return func(yield func(T) bool) { ... }. Inside it, first print each value that keep accepts, without calling yield, to check the filter. Then replace the print with a call to yield, and decide what the function must do when yield returns false.

Worked solution
Run the solution Go
package main

import (
	"fmt"
	"iter"
)

func Filtered[T any](values []T, keep func(T) bool) iter.Seq[T] {
	return func(yield func(T) bool) {
		for _, v := range values {
			if keep(v) && !yield(v) {
				return
			}
		}
	}
}

func main() {
	found := 0
	for q := range Filtered([]int{4, 12, 7, 30, 18}, func(n int) bool { return n > 10 }) {
		fmt.Println("Large:", q)
		found++
		if found == 2 {
			break
		}
	}
}
Text
Large: 12
Large: 30

18 also passes the filter, but the loop stopped first, so keep was never even asked about it. That laziness is the difference from Day 1's Filter, which checked every value and built a slice before the caller saw any of them.

Was this article helpful?

Your response is saved on this device.