Iterators and range over functions

suggest change

Since Go 1.23, for ... range works with functions as well as slices, maps, strings, channels and integers. A function you can range over is an iterator. It produces values by calling a callback, traditionally named yield, once per element.

range accepts a function with one of three signatures:

function type loop form
func(yield func() bool) for range f
func(yield func(V) bool) for v := range f
func(yield func(K, V) bool) for k, v := range f

The iter package names the last two iter.Seq[V] and iter.Seq2[K, V]. The slices, maps, strings and bytes packages return and accept these types.

A first iterator

package main

import "fmt"

// Countdown calls yield with n, n-1, ..., 1.
func Countdown(n int) func(yield func(int) bool) {
	return func(yield func(int) bool) {
		for i := n; i > 0; i-- {
			if !yield(i) {
				return
			}
		}
	}
}

func main() {
	for i := range Countdown(5) {
		fmt.Print(i, " ")
	}
	fmt.Println()

	for i := range Countdown(10) {
		if i == 7 {
			break
		}
		fmt.Print(i, " ")
	}
	fmt.Println()

	// range over an integer (Go 1.22) is the simplest built-in sequence
	for i := range 3 {
		fmt.Print(i, " ")
	}
	fmt.Println()
}
5 4 3 2 1 
10 9 8 
0 1 2 

Countdown doesn't return a slice. It returns a function that pushes values into the loop one at a time. The values are computed as they are needed, so Countdown(10) computes nothing past 7 once the loop breaks.

How the loop calls yield

The compiler turns the loop body into the yield function. yield returns true to ask for the next value and false when the loop is done, because of break, return, goto out of the loop, or a panic. Printing every step shows this:

package main

import "fmt"

func main() {
	countdown := func(yield func(int) bool) {
		for i := 3; i > 0; i-- {
			fmt.Println("  yielding", i)
			ok := yield(i)
			fmt.Println("  yield returned", ok)
			if !ok {
				return
			}
		}
		fmt.Println("  iterator done")
	}

	fmt.Println("loop with break:")
	for i := range countdown {
		fmt.Println("body got", i)
		if i == 2 {
			break
		}
	}

	fmt.Println("same as calling it directly:")
	countdown(func(i int) bool {
		fmt.Println("body got", i)
		return i != 2 // false means "stop"
	})
}
loop with break:
  yielding 3
body got 3
  yield returned true
  yielding 2
body got 2
  yield returned false
same as calling it directly:
  yielding 3
body got 3
  yield returned true
  yielding 2
body got 2
  yield returned false

The two forms do the same thing. The range version is easier to read, and break, continue and return work the same as in any other loop. A return in the loop body returns from the function that contains the loop, not from yield.

Zero and two values

An iterator can yield nothing, one value or two values:

package main

import "fmt"

// zero values: func(yield func() bool)
func times(n int) func(func() bool) {
	return func(yield func() bool) {
		for range n {
			if !yield() {
				return
			}
		}
	}
}

// two values: func(yield func(K, V) bool)
func enumerate(words []string) func(func(int, string) bool) {
	return func(yield func(int, string) bool) {
		for i, w := range words {
			if !yield(i+1, w) {
				return
			}
		}
	}
}

func main() {
	for range times(3) {
		fmt.Print("hip ")
	}
	fmt.Println("hooray")

	for n, w := range enumerate([]string{"alpha", "beta", "gamma"}) {
		fmt.Printf("%d. %s\n", n, w)
	}

	// like with maps, you can ignore the second value
	for n := range enumerate([]string{"x", "y"}) {
		fmt.Print(n, " ")
	}
	fmt.Println()
}
hip hip hip hooray
1. alpha
2. beta
3. gamma
1 2 

The two-value form is used for pairs such as index and element, key and value, or value and error.

iter.Seq and iter.Seq2

The iter package defines names for the two common shapes:

type Seq[V any] func(yield func(V) bool)
type Seq2[K, V any] func(yield func(K, V) bool)

By convention, a collection type gets methods that return iterators. All yields every element. Other names describe the order or subset, like Backward or Keys:

package main

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

// Stack is a LIFO collection.
type Stack[T any] struct {
	items []T
}

func (s *Stack[T]) Push(v T) { s.items = append(s.items, v) }

// All yields elements from top to bottom.
func (s *Stack[T]) All() iter.Seq[T] {
	return func(yield func(T) bool) {
		for i := len(s.items) - 1; i >= 0; i-- {
			if !yield(s.items[i]) {
				return
			}
		}
	}
}

// Indexed yields (depth, element) pairs, depth 0 being the top.
func (s *Stack[T]) Indexed() iter.Seq2[int, T] {
	return func(yield func(int, T) bool) {
		for i := len(s.items) - 1; i >= 0; i-- {
			if !yield(len(s.items)-1-i, s.items[i]) {
				return
			}
		}
	}
}

func main() {
	var s Stack[string]
	for _, v := range []string{"a", "b", "c"} {
		s.Push(v)
	}

	for v := range s.All() {
		fmt.Print(v, " ")
	}
	fmt.Println()

	for depth, v := range s.Indexed() {
		fmt.Printf("%d:%s ", depth, v)
	}
	fmt.Println()

	// iter.Seq works with every function that accepts iterators
	fmt.Println(slices.Collect(s.All()))
	fmt.Println(slices.Sorted(s.All()))
}
c b a 
0:c 1:b 2:a 
[c b a]
[a b c]

Callers can range over the stack without knowing how it stores its elements, and the stack doesn't have to copy them into a new slice. Recursive data structures work the same way. Recursion shows an in-order traversal of a binary tree as an iter.Seq. See Generics for more about type parameters.

Iterators in the standard library

Many standard library functions return iterators. Others consume them:

package main

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

func main() {
	names := []string{"bob", "alice", "carol"}

	for i, v := range slices.All(names) {
		fmt.Print(i, "=", v, " ")
	}
	fmt.Println()

	for v := range slices.Values(names) {
		fmt.Print(v, " ")
	}
	fmt.Println()

	for i, v := range slices.Backward(names) {
		fmt.Print(i, "=", v, " ")
	}
	fmt.Println()

	for c := range slices.Chunk([]int{1, 2, 3, 4, 5}, 2) {
		fmt.Print(c, " ")
	}
	fmt.Println()

	ages := map[string]int{"bob": 31, "alice": 28, "carol": 45}
	// maps.Keys returns an iterator; slices.Sorted collects and sorts it
	for _, k := range slices.Sorted(maps.Keys(ages)) {
		fmt.Print(k, "=", ages[k], " ")
	}
	fmt.Println()

	total := 0
	for age := range maps.Values(ages) {
		total += age
	}
	fmt.Println("total age:", total)

	text := "first line\nsecond line\nthird line\n"
	for line := range strings.Lines(text) {
		fmt.Printf("%q ", line)
	}
	fmt.Println()

	for part := range strings.SplitSeq("a,b,,c", ",") {
		fmt.Printf("%q ", part)
	}
	fmt.Println()

	for f := range strings.FieldsSeq("  lots   of\tspace  ") {
		fmt.Printf("%q ", f)
	}
	fmt.Println()

	// append iterator values to an existing slice
	all := slices.AppendSeq([]string{"dave"}, slices.Values(names))
	fmt.Println(all)
}
0=bob 1=alice 2=carol 
bob alice carol 
2=carol 1=alice 0=bob 
[1 2] [3 4] [5] 
alice=28 bob=31 carol=45 
total age: 104
"first line\n" "second line\n" "third line\n" 
"a" "b" "" "c" 
"lots" "of" "space" 
[dave bob alice carol]

The most useful ones:

function returns / does
slices.All(s) iter.Seq2[int, E] of index and element
slices.Values(s) iter.Seq[E] of elements
slices.Backward(s) iter.Seq2[int, E] from last to first
slices.Chunk(s, n) iter.Seq[[]E] of sub-slices of up to n elements
maps.All(m), maps.Keys(m), maps.Values(m) iterators over a map, in random order
strings.Lines, strings.SplitSeq, strings.FieldsSeq iterators over parts of a string (Go 1.24); bytes has the same functions
slices.Collect(seq) a new slice with all values
slices.Sorted(seq), slices.SortedFunc(seq, cmp) a sorted new slice
slices.AppendSeq(s, seq) s with all values appended
maps.Collect(seq2), maps.Insert(m, seq2) a new map, or values added to an existing map

strings.SplitSeq and strings.FieldsSeq don't allocate a result slice like strings.Split and strings.Fields do. Use them when you only loop over the parts.

To write lazy Map, Filter, Take and Reduce helpers on top of iter.Seq and chain them, see Map, filter, and reduce.

Always check the result of yield

When yield returns false, the iterator must stop calling it. Calling yield again is a bug, and the runtime panics:

package main

import "fmt"

// buggy ignores the result of yield
func buggy(yield func(int) bool) {
	for i := range 3 {
		yield(i)
	}
}

func main() {
	for v := range buggy {
		fmt.Println("got", v)
		if v == 1 {
			break
		}
	}
	fmt.Println("not reached")
}
got 0
got 1
panic: runtime error: range function continued iteration after function for loop body returned false

goroutine 1 [running]:
...

buggy works as long as every loop runs to the end, so the bug only shows up when someone adds a break. Write every iterator with if !yield(v) { return }. When the iterator calls a helper, for example a recursive one, the helper must return the result of yield to its caller so the whole traversal stops.

Cleanup with defer

An iterator is an ordinary function call, so defer inside it runs when the iteration ends. This happens when the loop finishes, when it breaks, when the loop body returns, and when it panics. This makes iterators a good fit for resources that must be released:

package main

import (
	"fmt"
	"iter"
)

type Conn struct{ name string }

func open(name string) *Conn {
	fmt.Println("open", name)
	return &Conn{name}
}

func (c *Conn) Close() { fmt.Println("close", c.name) }

// Rows opens a connection, yields rows and always closes the connection.
func Rows(name string) iter.Seq[string] {
	return func(yield func(string) bool) {
		c := open(name)
		defer c.Close()
		for i := 1; i <= 3; i++ {
			if !yield(fmt.Sprintf("%s row %d", c.name, i)) {
				return
			}
		}
	}
}

func firstRow(name string) string {
	for row := range Rows(name) {
		return row // returning from the loop body stops the iterator
	}
	return ""
}

func main() {
	for row := range Rows("db1") {
		fmt.Println(row)
	}

	fmt.Println("first:", firstRow("db2"))

	func() {
		defer func() { fmt.Println("recovered:", recover()) }()
		for row := range Rows("db3") {
			fmt.Println(row)
			panic("boom")
		}
	}()
}
open db1
db1 row 1
db1 row 2
db1 row 3
close db1
open db2
close db2
first: db2 row 1
open db3
db3 row 1
close db3
recovered: boom

The connection is opened when the loop starts, not when Rows is called, and it is closed in every case. The caller can't forget to call Close.

Don't call recover inside an iterator to catch panics from the loop body. A panic in the body should reach the code that contains the loop, as it does with any other for loop.

Iterators that can fail

yield has no error result. A common pattern for iterators that can fail, such as ones that read files or parse input, is iter.Seq2[T, error]:

package main

import (
	"bufio"
	"fmt"
	"io"
	"iter"
	"strconv"
	"strings"
)

// Numbers parses one integer per line. Each element is a value or an error.
func Numbers(r io.Reader) iter.Seq2[int, error] {
	return func(yield func(int, error) bool) {
		sc := bufio.NewScanner(r)
		line := 0
		for sc.Scan() {
			line++
			n, err := strconv.Atoi(strings.TrimSpace(sc.Text()))
			if err != nil {
				err = fmt.Errorf("line %d: %w", line, err)
			}
			if !yield(n, err) {
				return
			}
		}
		if err := sc.Err(); err != nil {
			yield(0, err)
		}
	}
}

func sum(r io.Reader) (int, error) {
	total := 0
	for n, err := range Numbers(r) {
		if err != nil {
			return 0, err
		}
		total += n
	}
	return total, nil
}

func main() {
	fmt.Println(sum(strings.NewReader("10\n20\n 30 \n")))
	fmt.Println(sum(strings.NewReader("10\ntwenty\n30\n")))
}
60 <nil>
0 line 2: strconv.Atoi: parsing "twenty": invalid syntax

The caller checks err on every iteration, like after any function call. It decides whether to stop or skip the bad element. Here it returns on the first error, which also stops the iterator.

Another option is the bufio.Scanner style: an iterator method plus an Err() method that the caller checks after the loop. It keeps the loop body simpler, but it's easy to forget the check.

Pull iterators: iter.Pull

The iterators so far are push iterators: the iterator controls the loop and pushes values into the body. Sometimes you need to pull values one at a time, for example to walk two sequences in step. A for loop can only range over one of them.

iter.Pull converts a push iterator into a next function and a stop function. iter.Pull2 does the same for iter.Seq2:

package main

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

// Merge yields elements of two sorted sequences in sorted order.
func Merge[T cmp.Ordered](a, b iter.Seq[T]) iter.Seq[T] {
	return func(yield func(T) bool) {
		nextA, stopA := iter.Pull(a)
		defer stopA()
		nextB, stopB := iter.Pull(b)
		defer stopB()

		va, okA := nextA()
		vb, okB := nextB()
		for okA || okB {
			if okA && (!okB || va <= vb) {
				if !yield(va) {
					return
				}
				va, okA = nextA()
			} else {
				if !yield(vb) {
					return
				}
				vb, okB = nextB()
			}
		}
	}
}

// Zip yields pairs of elements from a and b until either one ends.
func Zip[A, B any](a iter.Seq[A], b iter.Seq[B]) iter.Seq2[A, B] {
	return func(yield func(A, B) bool) {
		nextB, stop := iter.Pull(b)
		defer stop()
		for va := range a {
			vb, ok := nextB()
			if !ok || !yield(va, vb) {
				return
			}
		}
	}
}

func main() {
	next, stop := iter.Pull(slices.Values([]string{"a", "b", "c"}))
	fmt.Println(next())
	fmt.Println(next())
	stop() // we don't need the rest
	fmt.Println(next())

	odd := slices.Values([]int{1, 3, 5, 7, 9})
	even := slices.Values([]int{2, 4, 6})
	fmt.Println(slices.Collect(Merge(odd, even)))

	names := slices.Values([]string{"alice", "bob", "carol"})
	scores := slices.Values([]int{90, 85})
	for name, score := range Zip(names, scores) {
		fmt.Println(name, score)
	}
}
a true
b true
 false
[1 2 3 4 5 6 7 9]
alice 90
bob 85

Rules for pull iterators:

Zip pulls from only one sequence and ranges over the other, which is simpler and cheaper. Pulling has a cost: iter.Pull runs the iterator as a coroutine, so each next() is a switch between stacks. It's much cheaper than goroutines and channels, but slower than a plain range. Use push iterators unless you really need to pull.

Single-use and reusable iterators

Most iterators, like slices.Values or the Stack.All above, can be ranged over many times, and each loop starts from the beginning. Iterators that read from a stream can't be restarted. Each loop continues where the previous one stopped:

package main

import (
	"bufio"
	"fmt"
	"iter"
	"slices"
	"strings"
)

// Words is single-use: it consumes the underlying scanner.
func Words(sc *bufio.Scanner) iter.Seq[string] {
	return func(yield func(string) bool) {
		for sc.Scan() {
			if !yield(sc.Text()) {
				return
			}
		}
	}
}

func main() {
	sc := bufio.NewScanner(strings.NewReader("one two three four"))
	sc.Split(bufio.ScanWords)
	words := Words(sc)

	for w := range words {
		fmt.Println("first loop:", w)
		if w == "two" {
			break
		}
	}
	// continues where the previous loop stopped
	fmt.Println("second loop:", slices.Collect(words))
	fmt.Println("third loop:", slices.Collect(words))

	// slices.Values is reusable: every range starts from the beginning
	nums := slices.Values([]int{1, 2, 3})
	fmt.Println(slices.Collect(nums), slices.Collect(nums))
}
first loop: one
first loop: two
second loop: [three four]
third loop: []
[1 2 3] [1 2 3]

Document whether your iterator is single-use. If callers need to loop more than once over a single-use or expensive sequence, they should collect it into a slice with slices.Collect first.

Things to keep in mind

Summary

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents