Go core
Browse topics

Iterators and range over functions

Version
1.27
Since
1.23
Review
Draft

Summary#

An iterator is a function that passes values to a yield callback. A for range loop can consume it. yield returns false when the loop stops early, so the iterator must stop yielding.

Syntax#

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

for value := range sequence {
}

Example#

go
package main

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

func countdown(from int) iter.Seq[int] {
	return func(yield func(int) bool) {
		defer fmt.Println("iterator returned")
		for n := from; n > 0; n-- {
			if !yield(n) {
				return
			}
		}
	}
}

func main() {
	for n := range countdown(5) {
		fmt.Println(n)
		if n == 4 {
			break
		}
	}

	fmt.Println(slices.Collect(countdown(3)))
}

Expected output#

Text
5
4
iterator returned
iterator returned
[3 2 1]

Common mistakes#

Ignoring the result of yield and calling it again after it returned false causes a panic. Return as soon as it reports false. When you consume a sequence with iter.Pull, call its stop function if you may leave before the end, usually with defer stop().

Version applicability#

Go 1.23 added the iter package, ranging over iterator functions and slices.Collect. The complete example requires Go 1.23 or later. On earlier versions, expose a callback method or return a slice.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0