System Design

G6

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.

Not startedSaved in this browser only.
  1. 1An iterator is a function that calls yield. The loop body is yield. Stop when yield returns false.
  2. 2A defer in an iterator runs before the code after the loop. A defer in the loop body runs when the enclosing function returns.
  3. 3A closure captures variables, not values. Since Go 1.22, each loop iteration has new variables.
  4. 4Defer runs last in, first out. Go evaluates its arguments at the defer statement, not when the call runs.
G6
    A

    The trap

    one missing check
    an iterator that ignores yieldgo
    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
        }
      }
    }
    1. 1The result is dropped. The loop keeps going after the body said stop.
    2. 2A break makes yield return false. The iterator must return now.
    iteratorrecorded last linestatus
    yield(v)panic: runtime error: range function continued iteration after function for loop body returned falsePanics on break
    if !yield(v) { return }2Approved
    • 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.

    B

    The model: the body is a function

    the Go specification, range over function
    stack during one iteration, top is newestmainthe for statementCountdown iteratorits loop, its defersloop body, as yieldreturns true to continuecalls iterator(yield)calls yield(v)break or return: yield returns false to the iterator
    • 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.

    C

    The rules: the yield contract

    iter package documentation
    rulestatus
    Return when yield returns falseApproved
    Use defer for cleanupApproved
    Call yield after falsePanics
    Keep yield and call it after returnPanics
    Recover a body panic and returnPanics

    After false, I return. I never call yield after the loop ends, and I never start a goroutine that calls it.

    D

    See it: who runs when

    recorded from one iterator
    1. 1open the source
    2. 2call yield(1)
    3. 3body runs with 1
    4. 4yield returned true: continue
    5. 5call yield(2)
    6. 6body runs with 2
    7. 7yield returned true: continue
    8. 8call yield(3)
    9. 9body runs with 3
    10. 10yield returned true: continue
    11. 11source is empty: return
    12. 12deferred cleanup runs
    13. 13code after the loop
    Step 1 of 13, in iterator.
    • 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.

    E

    Push or pull

    numbers measured in the lab
    formcost per valueuse it whenavoid it whenstatus
    for over a slice1.2 nsYou hold the slice.The caller must not depend on the storage.Approved
    iter.Seq, range2.1 nsYou expose a sequence, or one you cannot hold in memory.Callers need random access or a length.Approved
    three adapters3.5 nsThe chain reads better than one loop.One loop with two ifs is clearer.If it reads better
    iter.Pull66.6 nsYou merge or zip two sequences.A range loop can do the work.Two sequences at once
    goroutine and channel217 nsThe 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.

    F

    The library iterators

    use these first
    sincepackageiterators
    1.23slicesAll, Values, Backward, Chunk return one. Collect, AppendSeq, Sorted, SortedFunc, SortedStableFunc take one.
    1.23mapsAll, Keys, Values return one. Insert and Collect take one.
    1.24strings, bytesLines, SplitSeq, SplitAfterSeq, FieldsSeq, FieldsFuncSeq.
    1.26reflectType.Fields, Type.Methods, Type.Ins, Type.Outs, Value.Fields, Value.Methods.
    stdlibgo
    // 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
    }
    1. 1Map order is random. Sorted collects and sorts in one call.
    2. 2Each chunk shares the array of ids, and its capacity is clipped.
    3. 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.

    G

    A push iterator

    tested
    countdowngo
    // 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
          }
        }
      }
    }
    1. 1iter.Seq[V] is func(yield func(V) bool). iter.Seq2[K, V] yields two values.
    2. 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.

    H

    Adapters

    tested
    adaptersgo
    // 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
          }
        }
      }
    }
    1. 1A range over the input, so an early stop reaches the source with no extra code.
    2. 2Yield only what passes. Return only when yield says stop.
    3. 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.

    I

    Cleanup and errors

    tested on all three exits
    linesgo
    // 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
        }
      }
    }
    1. 1The usual form for a source that can fail. The caller checks err in the body.
    2. 2Runs on end of input, a read error, or a break.
    3. 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.

    J

    Pull: merge two sequences

    tested
    mergego
    // 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()
        }
      }
    }
    1. 1next gives one value at a time. The iterator waits in between.
    2. 2Without stop, the coroutine and its cleanup stay pending.
    3. 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.

    K

    A recursive iterator

    tested
    treego
    // 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)
    }
    1. 1The helper keeps the bool that the public iterator does not return.
    2. 2If the helper returned nothing, a break would reach the right subtree and panic.
    3. 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.

    L

    Loop variables

    both programs ran on Go 1.27.3
    the old rule, set by a build linego
    //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()
    }
    1. 1A build line can lower the language version of one file. This file gets the old rule.
    2. 2Under the old rule, each closure captures the one i.
    language versionrecorded outputstatus
    go1.213 3 3All share one i
    go1.22 or later0 1 2Approved
    • 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.

    M

    Closures

    what is captured
    formwhat it bindswhen
    func() { use(x) }The variable xReads x when it runs
    func(x int) {...}(x)A copy of the valueAt the call
    v.Method, value receiverA copy of vAt that expression
    v.Method, pointer receiver&vAt that expression
    go f(x), defer f(x)f and a copy of xAt 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.

    N

    Closures that hold state

    tested
    countergo
    // 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
      }
    }
    1. 1A new variable per call to Counter. It outlives the call, so it lives on the heap.
    2. 2Not safe for concurrent use: this is a plain read and write.
    optiongo
    // 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
    }
    1. 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.

    O

    The rules: defer

    the Go specification, and the drill below
    ruleconsequencestatus
    Deferred calls run last in, first outRelease in reverse order of acquire, with no extra code.Approved
    Arguments and the receiver are evaluated at the defer statementA later change is not seen. Use a closure to read the final value.Approved
    A deferred closure can write a named resultUse it to add a Close error to err. See G7.Approved
    Defer in an iteratorRuns when the iterator returns, before the code after the loop.Approved
    Defer in a range-over-func bodyBelongs to the enclosing function, as in any loop.At function end
    Defer in a long loopEach call waits until the function returns, so resources pile up.Use a helper
    Rely on defer after os.Exit or log.FatalThe 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.

    P

    Defer in a loop

    tested
    deferloopgo
    // 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
    }
    1. 1The helper gives each iteration its own function scope for defer.
    2. 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.

    Q

    New in recent Go

    checked against each release's notes
    sincewhat changedwhat it means here
    1.21Built-ins min, max and clear. A preview of per-iteration loop variables behind an experiment.The preview became the rule in 1.22.
    1.22Each 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.23Range over function types. The iter package. Iterator functions in slices and maps.Panels A to K.
    1.24Iterator functions in strings and bytes. go/types exposes iterators. text/template ranges over functions and integers.strings.FieldsSeq in panel F.
    1.26reflect iterators for fields, methods and parameters.Panel F.
    1.27go fix gains the slicesbackward modernizer. The language has no iterator change.Older loops can move to slices.Backward with go fix.
    R

    In the round

    45 minutes of build, 45 minutes of talk
    whenthe momentwhat to do or say
    buildA list endpoint must return sorted keys.Use slices.Sorted(maps.Keys(m)) under the lock. Map order is random, so tests need this.
    buildYou start goroutines in a loop.Capture the loop variable directly. Say that Go 1.22 made each iteration new.
    buildYou 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.

    S

    Drill

    each answer is the output of a real run

    0 of 12 known

    1. 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")
      }
    2. 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")
      }
    3. 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
        }
      }
    4. 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()
      }
    5. 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")
      }
    6. 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)))
      }
    7. 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
        }
      }
    8. 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()
      }
    9. 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())
      }
    10. Predict the output.

      package main
      
      import "fmt"
      
      func main() {
        x := 1
        defer fmt.Println("argument:", x)
        defer func() { fmt.Println("closure:", x) }()
        x = 2
      }
    11. 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())
      }
    12. 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")
      }
    T

    Numbers to say

    measured with testing.B
    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.