Iterators and closures
A range loop can now call a function, and the loop body becomes a closure. Here is how that works, what stops it, how cleanup runs, and the closure and defer rules behind it.
- 1An iterator is a function that calls yield. The loop body is yield. Stop when yield returns false.
- 2A defer in an iterator runs before the code after the loop. A defer in the loop body runs when the enclosing function returns.
- 3A closure captures variables, not values. Since Go 1.22, each loop iteration has new variables.
- 4Defer runs last in, first out. Go evaluates its arguments at the defer statement, not when the call runs.
package main
import "fmt"
func Each(s []int) func(func(int) bool) {
return func(yield func(int) bool) {
for _, v := range s {
yield(v)
}
}
}
func main() {
for v := range Each([]int{1, 2, 3}) {
fmt.Println(v)
if v == 2 {
break2
}
}
}- 1The result is dropped. The loop keeps going after the body said stop.
- 2A break makes yield return false. The iterator must return now.
| iterator | recorded last line | status |
|---|---|---|
| yield(v) | panic: runtime error: range function continued iteration after function for loop body returned false | Panics on break |
| if !yield(v) { return } | 2 | Approved |
- The bug hides until a caller stops early. A test that ranges to the end passes.
- A return or a labeled break in the body makes yield return false in the same way.
- Test every iterator with a break on the first value.
An iterator must stop when yield returns false. If it calls yield again, the runtime panics.
- The compiler rewrites break, continue, return and goto in the body, so they act on the outer loop.
- All iteration happens on one goroutine. No channel and no lock is involved.
- The measured loop over slices.Values made 0 allocations, so the body closure stayed on the stack.
The compiler turns the loop body into a function and passes it as yield. The body runs on top of the iterator's frame.
| rule | status |
|---|---|
| Return when yield returns false | Approved |
| Use defer for cleanup | Approved |
| Call yield after false | Panics |
| Keep yield and call it after return | Panics |
| Recover a body panic and return | Panics |
After false, I return. I never call yield after the loop ends, and I never start a goroutine that calls it.
- 1open the source
- 2call yield(1)
- 3body runs with 1
- 4yield returned true: continue
- 5call yield(2)
- 6body runs with 2
- 7yield returned true: continue
- 8call yield(3)
- 9body runs with 3
- 10yield returned true: continue
- 11source is empty: return
- 12deferred cleanup runs
- 13code after the loop
- The deferred cleanup runs before the code after the loop, on both paths.
- iter.Pull starts nothing until the first next. stop returns only after the cleanup ran.
In a push loop the iterator and the body take turns on one stack. Pull hands the iterator a coroutine, so stop must run.
| form | cost per value | use it when | avoid it when | status |
|---|---|---|---|---|
| for over a slice | 1.2 ns | You hold the slice. | The caller must not depend on the storage. | Approved |
| iter.Seq, range | 2.1 ns | You expose a sequence, or one you cannot hold in memory. | Callers need random access or a length. | Approved |
| three adapters | 3.5 ns | The chain reads better than one loop. | One loop with two ifs is clearer. | If it reads better |
| iter.Pull | 66.6 ns | You merge or zip two sequences. | A range loop can do the work. | Two sequences at once |
| goroutine and channel | 217 ns | The work really runs in parallel. | You only want an iterator. | As an iterator |
iter.Pull switches coroutines, with no scheduler call. It costs about 31 times a push iterator, and a channel costs about 3 times Pull. Run on a busy machine.
I use a range loop by default. I use iter.Pull when I walk two sequences together, and I always defer stop.
| since | package | iterators |
|---|---|---|
| 1.23 | slices | All, Values, Backward, Chunk return one. Collect, AppendSeq, Sorted, SortedFunc, SortedStableFunc take one. |
| 1.23 | maps | All, Keys, Values return one. Insert and Collect take one. |
| 1.24 | strings, bytes | Lines, SplitSeq, SplitAfterSeq, FieldsSeq, FieldsFuncSeq. |
| 1.26 | reflect | Type.Fields, Type.Methods, Type.Ins, Type.Outs, Value.Fields, Value.Methods. |
// TopKeys returns the keys of m with a count of at least
// min, in sorted order, using only library iterators.
func TopKeys(m map[string]int, min int) []string {
var out []string
for _, k := range slices.Sorted(maps.Keys(m))1 {
if m[k] >= min {
out = append(out, k)
}
}
return out
}
// Batches splits ids into groups for a bulk call.
func Batches(ids []int, size int) [][]int {
return slices.Collect(slices.Chunk(ids, size)2)
}
// Words counts words with the Go 1.24 iterator form, so
// no slice of fields is built.
func Words(s string) int {
n := 0
for range strings.FieldsSeq(s)3 {
n++
}
return n
}- 1Map order is random. Sorted collects and sorts in one call.
- 2Each chunk shares the array of ids, and its capacity is clipped.
- 3No slice of fields, so no allocation for it.
slices.Sorted of maps.Keys gives sorted keys in one line. strings.SplitSeq avoids building a slice.
// Countdown returns a push iterator. The loop body runs
// inside each yield call.
func Countdown(from int) iter.Seq[int]1 {
return func(yield func(int) bool) {
for i := from; i > 0; i-- {
if !yield(i) {2
return
}
}
}
}- 1iter.Seq[V] is func(yield func(V) bool). iter.Seq2[K, V] yields two values.
- 2The check from panel A.
The return type is iter.Seq, so a caller can range over the result and pass it to slices.Collect.
// Filter passes on the values that pass the test.
func Filter[T any](s iter.Seq[T], keep func(T) bool) iter.Seq[T] {
return func(yield func(T) bool) {
for v := range s {1
if keep(v) && !yield(v)2 {
return
}
}
}
}
// Map applies f to each value.
func Map[T, U any](s iter.Seq[T], f func(T) U) iter.Seq[U] {
return func(yield func(U) bool) {
for v := range s {
if !yield(f(v)) {
return
}
}
}
}
// Take stops after n values.
func Take[T any](s iter.Seq[T], n int) iter.Seq[T] {
return func(yield func(T) bool) {
if n <= 0 {
return
}
seen := 0
for v := range s {
if !yield(v) {
return
}
seen++
if seen == n {3
return
}
}
}
}- 1A range over the input, so an early stop reaches the source with no extra code.
- 2Yield only what passes. Return only when yield says stop.
- 3Take stops after value n, not on value n + 1. So it never reads a value it drops.
Adapters are lazy. Nothing runs until a range loop starts, and a break stops the source.
// Lines yields each line and an error. The defer runs on
// every exit: end of input, a read error, or a break. It
// logs a close error: yield may not run after a break.
func Lines(open func() (io.ReadCloser, error)) iter.Seq2[string, error]1 {
return func(yield func(string, error) bool) {
f, err := open()
if err != nil {
yield("", fmt.Errorf("open: %w", err))
return
}
defer func() {2
if err := f.Close(); err != nil {
log.Printf("close: %v", err)
}
}()
sc := bufio.NewScanner(f)
for sc.Scan() {
if !yield(sc.Text(), nil) {
return
}
}
if err := sc.Err(); err != nil {
yield("", fmt.Errorf("scan: %w", err))3
}
}
}- 1The usual form for a source that can fail. The caller checks err in the body.
- 2Runs on end of input, a read error, or a break.
- 3The last yield. Its result does not matter, because the function returns next.
A sequence that can fail yields a value and an error, and defer closes the source on every exit.
// Merge joins two sorted sequences into one. Two inputs
// cannot both push, so Pull turns each one into a next.
func Merge[T cmp.Ordered](a, b iter.Seq[T]) iter.Seq[T] {
return func(yield func(T) bool) {
nextA, stopA := iter.Pull(a)1
defer stopA()2
nextB, stopB := iter.Pull(b)
defer stopB()
x, okX := nextA()
y, okY := nextB()
for okX || okY {3
if okX && (!okY || x <= y) {
if !yield(x) {
return
}
x, okX = nextA()
continue
}
if !yield(y) {
return
}
y, okY = nextB()
}
}
}- 1next gives one value at a time. The iterator waits in between.
- 2Without stop, the coroutine and its cleanup stay pending.
- 3Run until both sides are empty.
Two inputs cannot both push, so I pull from each. A deferred stop ends both coroutines on an early exit.
// Tree is a binary search tree of ints.
type Tree struct {
Left, Right *Tree
Value int
}
// All walks the tree in order. A recursive walk must
// pass the stop signal up through every call.
func (t *Tree) All() iter.Seq[int] {
return func(yield func(int) bool) {
t.walk(yield)1
}
}
func (t *Tree) walk(yield func(int) bool) bool2 {
if t == nil {
return true
}
return t.Left.walk(yield) &&
yield(t.Value) &&3
t.Right.walk(yield)
}- 1The helper keeps the bool that the public iterator does not return.
- 2If the helper returned nothing, a break would reach the right subtree and panic.
- 3A false result skips the right subtree, and returns false to the caller.
In a recursive walk, the stop signal must travel up. So the helper returns a bool, and && stops the walk.
//go:build go1.211
package main
import "fmt"
func main() {
var print []func()
for i := 0; i < 3; i++ {
print = append(print, func() { fmt.Print(i, " ") }2)
}
for _, f := range print {
f()
}
fmt.Println()
}- 1A build line can lower the language version of one file. This file gets the old rule.
- 2Under the old rule, each closure captures the one i.
| language version | recorded output | status |
|---|---|---|
| go1.21 | 3 3 3 | All share one i |
| go1.22 or later | 0 1 2 | Approved |
- The rule depends on the go line in go.mod and on build lines, not on the toolchain.
- The copy i := i before a go statement is no longer needed. Remove it when you touch the code.
- A three-clause loop copies i into a new variable before the post statement. So a closure from one iteration never sees the next increment.
- A variable declared outside the loop is still shared. The change covers only variables that the loop declares.
Since Go 1.22, each iteration has its own variables, for files whose language version is 1.22 or later.
| form | what it binds | when |
|---|---|---|
| func() { use(x) } | The variable x | Reads x when it runs |
| func(x int) {...}(x) | A copy of the value | At the call |
| v.Method, value receiver | A copy of v | At that expression |
| v.Method, pointer receiver | &v | At that expression |
| go f(x), defer f(x) | f and a copy of x | At the statement |
A closure that stays on the stack costs 2.5 ns. One that escapes costs 22.2 ns and 2 allocations here.
A closure holds a reference to the variable. If the closure outlives the function, the variable moves to the heap.
// Counter returns a function that holds its own state.
// The variable n escapes to the heap, and only this
// closure can reach it.
func Counter() func() int {
n := 01
return func() int {
n++2
return n
}
}- 1A new variable per call to Counter. It outlives the call, so it lives on the heap.
- 2Not safe for concurrent use: this is a plain read and write.
// Server is built by functional options.
type Server struct {
Addr string
Max int
}
// Option changes one field of a Server.
type Option func(*Server)
// WithMax captures n in a closure for New to run later.
func WithMax(n int) Option {
return func(s *Server) { s.Max = n }1
}
// New applies the options in order.
func New(addr string, opts ...Option) *Server {
s := &Server{Addr: addr, Max: 10}
for _, opt := range opts {
opt(s)
}
return s
}- 1A closure carries n until New runs it. These are functional options.
Each call to Counter makes a new n, so two counters share nothing. For one worker this replaces a small struct.
| rule | consequence | status |
|---|---|---|
| Deferred calls run last in, first out | Release in reverse order of acquire, with no extra code. | Approved |
| Arguments and the receiver are evaluated at the defer statement | A later change is not seen. Use a closure to read the final value. | Approved |
| A deferred closure can write a named result | Use it to add a Close error to err. See G7. | Approved |
| Defer in an iterator | Runs when the iterator returns, before the code after the loop. | Approved |
| Defer in a range-over-func body | Belongs to the enclosing function, as in any loop. | At function end |
| Defer in a long loop | Each call waits until the function returns, so resources pile up. | Use a helper |
| Rely on defer after os.Exit or log.Fatal | The process ends at once, so no deferred call runs. | Not approved |
A defer costs 2.7 ns against 1.2 ns for the same call with no defer. Use it by default on any path that is not hot.
Defer runs last in, first out at function return. The arguments are fixed at the defer statement, and a deferred closure can change a named result.
// Opener opens one named file.
type Opener func(string) (io.ReadCloser, error)
// CopyAll closes each file at the end of its iteration.
// A defer in the loop would hold every file open until
// CopyAll returns, so the loop body is a function.
func CopyAll(names []string, open Opener, w io.Writer) error {
for _, name := range names {
if err := copyOne(name, open, w)1; err != nil {
return fmt.Errorf("copy %s: %w", name, err)
}
}
return nil
}
func copyOne(name string, open Opener, w io.Writer) (err error) {
f, err := open(name)
if err != nil {
return err
}
defer func() { err = errors.Join(err, f.Close()) }()2
_, err = io.Copy(w, f)
return err
}- 1The helper gives each iteration its own function scope for defer.
- 2Runs at the end of each helper call. It also keeps the Close error.
I move the loop body to a function, so each file closes at the end of its iteration.
| since | what changed | what it means here |
|---|---|---|
| 1.21 | Built-ins min, max and clear. A preview of per-iteration loop variables behind an experiment. | The preview became the rule in 1.22. |
| 1.22 | Each iteration of a for loop creates new variables. Range over an integer. vet stops the loop variable report for files with the new rule. | Panel L. for i := range n. |
| 1.23 | Range over function types. The iter package. Iterator functions in slices and maps. | Panels A to K. |
| 1.24 | Iterator functions in strings and bytes. go/types exposes iterators. text/template ranges over functions and integers. | strings.FieldsSeq in panel F. |
| 1.26 | reflect iterators for fields, methods and parameters. | Panel F. |
| 1.27 | go fix gains the slicesbackward modernizer. The language has no iterator change. | Older loops can move to slices.Backward with go fix. |
| when | the moment | what to do or say |
|---|---|---|
| build | A list endpoint must return sorted keys. | Use slices.Sorted(maps.Keys(m)) under the lock. Map order is random, so tests need this. |
| build | You start goroutines in a loop. | Capture the loop variable directly. Say that Go 1.22 made each iteration new. |
| build | You hold a mutex. | Write defer mu.Unlock() on the next line. Do not range over a live map from outside the lock. |
| talk | "Return a slice or an iterator?" | A slice is simple and can be retried. An iterator suits large results and early stops. |
| talk | "An iterator holds a database cursor. What closes it?" | A defer in the iterator. It runs on every exit, also on a break. |
| talk | "Why not a channel as an iterator?" | It costs about 102 times more, and a caller that stops early leaks the goroutine. |
| talk | "Why does this print 3 3 3?" | The file is on an old language version. Check the go line in go.mod. |
I return a slice from the store unless the data is too large for memory. Then I return an iterator that yields an error.
0 of 12 known
Predict the output. The iterator never ends by itself.
package main import "fmt" func Rows(yield func(int) bool) { fmt.Println("open") defer fmt.Println("close") for i := 1; ; i++ { if !yield(i) { fmt.Println("stop seen") return } } } func main() { for v := range Rows { fmt.Println("row", v) if v == 2 { break } } fmt.Println("after the loop") }Predict the output.
package main import ( "fmt" "slices" ) func main() { for v := range slices.Values([]int{1, 2}) { defer fmt.Println("deferred", v) fmt.Println("body", v) } fmt.Println("after the loop") }Predict the output.
package main import ( "fmt" "iter" "slices" ) func Map(s iter.Seq[int], name string) iter.Seq[int] { return func(yield func(int) bool) { for v := range s { fmt.Println(name, v) if !yield(v * 10) { return } } } } func main() { s := Map(Map(slices.Values([]int{1, 2, 3}), "a"), "b") fmt.Println("built") for v := range s { fmt.Println("body", v) break } }Predict the output.
package main import ( "fmt" "iter" ) func Rows() iter.Seq[int] { return func(yield func(int) bool) { defer fmt.Println("cleanup") for i := 1; ; i++ { if !yield(i) { return } } } } func main() { next, stop := iter.Pull(Rows()) fmt.Println(next()) fmt.Println(next()) stop() fmt.Println(next()) stop() }Predict the output.
package main import "fmt" func Safe(yield func(int) bool) { defer func() { fmt.Println("recover:", recover()) }() yield(1) } func main() { defer func() { fmt.Println("main:", recover()) }() for range Safe { panic("body") } fmt.Println("after the loop") }Predict the output.
package main import ( "fmt" "slices" "strings" ) func main() { s := strings.Lines("a\nb\n") fmt.Println(len(slices.Collect(s)), len(slices.Collect(s))) ch := make(chan int, 2) ch <- 1 ch <- 2 close(ch) once := func(yield func(int) bool) { for v := range ch { if !yield(v) { return } } } fmt.Println(len(slices.Collect(once)), len(slices.Collect(once))) }Predict the output.
package main import "fmt" func main() { n := 3 for i := range n { n = 1 fmt.Print(i, " ") } fmt.Println() for i := range uint8(2) { fmt.Printf("%T ", i) } fmt.Println() for range -1 { fmt.Println("never") } const big = 1 << 40 for i := range big { fmt.Printf("%T\n", i) break } }Predict the output.
package main import "fmt" func main() { var get []func() int for i := 0; i < 6; i++ { get = append(get, func() int { return i }) i += 2 } for _, f := range get { fmt.Print(f(), " ") } fmt.Println() }Predict the output.
package main import "fmt" type Counter struct{ n int } func (c Counter) Value() int { return c.n } func (c *Counter) Add() { c.n++ } func main() { c := Counter{} byValue := c.Value add := c.Add add() add() fmt.Println(byValue(), c.Value()) }Predict the output.
package main import "fmt" func main() { x := 1 defer fmt.Println("argument:", x) defer func() { fmt.Println("closure:", x) }() x = 2 }Predict the output.
package main import "fmt" func named() (n int) { defer func() { n *= 2 }() return 21 } func unnamed() int { n := 21 defer func() { n *= 2 }() return n } func main() { fmt.Println(named(), unnamed()) }Predict the output.
package main import "fmt" type T struct{ name string } func (t T) Close() { fmt.Println("close", t.name) } func main() { defer func() { fmt.Println("recovered:", recover()) }() var t *T defer t.Close() fmt.Println("after the defer statement") }
- slice loop
- 1.2 ns per value.
- range-over-func
- 2.1 ns per value and 0 allocations.
- three adapters
- 3.5 ns per value.
- iter.Pull
- 66.6 ns per value.
- channel
- 217 ns per value.
- defer
- 2.7 ns a call, against 1.2 ns with no defer.
- closure
- 2.5 ns on the stack; 22.2 ns when it escapes.
Go 1.27.3, 8-core Intel i9 laptop, GOMAXPROCS 16, median of 5 interleaved runs of 1 s, on a busy machine. Use these as orders of magnitude.