Closures, capture and range-over-func

A function value is a value like any other: it can be stored, passed, returned and called. When it is a function literal that names variables from the surrounding function, it is a closure, and those variables live as long as the closure does, on the heap if necessary. The functions lesson introduced the value; this one uses the state it carries.

A closure with state

The factory declares n, returns two closures that share it, and every call of the factory makes a new n. Neither closure takes an argument, and neither reaches a package-level variable: the state is between them, which is encapsulation without a type or a struct. The compiler moves n to the heap because its lifetime outlives the call.

package main import "fmt" func counter() (func() int, func()) { n := 0 inc := func() int { n++ return n } reset := func() { n = 0 } return inc, reset } func main() { inc, reset := counter() inc() inc() fmt.Println("after two:", inc()) reset() fmt.Println("after reset:", inc()) other, _ := counter() fmt.Println("other counter:", other()) }

go run counter.go

after two: 3
after reset: 1
other counter: 1

The two counters were independent, so the reset of one had no effect on the other. This is the pattern behind http.HandlerFunc middleware and every test helper that hands out a function with its own fixture.

Capture in a loop

Before Go 1.22 all iterations shared one loop variable, so a closure appended to a slice printed the final value three times. Since Go 1.22 each iteration has its own variable, and the closures print 0, 1 and 2 without the i := i line that older code needed. The change is per module language version: a module that still declares go 1.21 keeps the old rule.

package main import "fmt" func main() { var funcs []func() int for i := 0; i < 3; i++ { funcs = append(funcs, func() int { return i }) } for _, f := range funcs { fmt.Print(f(), " ") } fmt.Println() total := 0 base := 10 for i := 0; i < 3; i++ { total += func() int { return base + i }() } fmt.Println("total:", total) }

go run loopvar.go

0 1 2
total: 33

The second loop called each closure immediately, which never had the problem: the call happened while the variable still held that iteration's value, and the sum is 33. The bug only appears when the call is deferred, stored or sent to a goroutine.

Functions that build functions

A function can return a function with some arguments fixed, which is how a configuration is turned into a reusable transformation. adder(10) is a function that adds ten, and it can be passed to anything that takes a func(int) int, including a generic-looking map written by hand. The captured base is read-only in practice, which keeps the value safe to share.

package main import "fmt" func adder(base int) func(int) int { return func(x int) int { return base + x } } func apply(nums []int, f func(int) int) []int { out := make([]int, 0, len(nums)) for _, n := range nums { out = append(out, f(n)) } return out } func main() { add10 := adder(10) fmt.Println(add10(5), add10(-2)) nums := []int{1, 2, 3} fmt.Println(apply(nums, add10)) fmt.Println(apply(nums, func(n int) int { return n * n })) }

go run curry.go

15 8
[11 12 13]
[1 4 9]

The same slice went through two functions and came back transformed, and the closures did not touch the input. A closure that writes to a captured variable is a small piece of mutable state, so it needs the same care as a field: no sharing across goroutines without a lock.

range over a function

Since Go 1.23 a function with the signature func(yield func(T) bool) can be the subject of a range loop. The loop calls the function once, and the function calls yield per element; a false result means the loop was left with a break or a return, so the producer should stop. This is how maps.Keys and slices.Values work, and it lets a custom sequence use the loop syntax without an interface.

package main import "fmt" func Count(n int) func(yield func(int) bool) { return func(yield func(int) bool) { for i := 1; i <= n; i++ { if !yield(i) { return } } } } func main() { sum := 0 for v := range Count(5) { sum += v } fmt.Println("sum:", sum) for v := range Count(100) { if v > 3 { break } fmt.Print(v, " ") } fmt.Println() }

go run iter.go

sum: 15
1 2 3

The first loop summed all five values; the second stopped after three because the break made yield return false and the producer returned. The iterator is lazy, so a sequence of a million values costs nothing until it is consumed, and the loop body keeps its normal break, continue and return.

Exercises

  1. Write a factory that returns a closure appending to a private slice and a second closure returning a copy of it. Why must the getter copy?
  2. Store closures in a loop before and after the Go 1.22 rule and explain the difference in one sentence. Which language version is your module?
  3. Write an iterator over the lines of a string with strings.Lines and one by hand with the yield signature. Which is shorter, and what does the standard one do with a final empty line?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does a closure keep alive?

    Answer

    The variables of the surrounding function that it names

    Captured variables live as long as the closure, on the heap when the call has returned.

  2. What does this program print? package main import "fmt" func counter() (func() int, func()) { n := 0 inc := func() int { n++ return n } reset := func() { n = 0 } return inc, reset } func main() { inc, reset := counter() inc() inc() fmt.Println("after two:", inc()) reset() fmt.Println("after reset:", inc()) other, _ := counter() fmt.Println("other counter:", other()) }

    Answer

    after two: 3 / after reset: 1 / other counter: 1

    The third call returned 3, the reset made the next call 1 again, and the second factory has its own n.

  3. What changed about loop variables in Go 1.22?

    Answer

    Each iteration has its own variable

    The per-iteration variable removed the classic i := i workaround.

  4. What does the first line of this program print? package main import "fmt" func main() { var funcs []func() int for i := 0; i < 3; i++ { funcs = append(funcs, func() int { return i }) } for _, f := range funcs { fmt.Print(f(), " ") } fmt.Println() total := 0 base := 10 for i := 0; i < 3; i++ { total += func() int { return base + i }() } fmt.Println("total:", total) }

    Answer

    0 1 2 / total: 33

    Each closure captured its own iteration variable, so the values are distinct.

  5. What is a function that returns a function with an argument fixed called?

    Answer

    A partial application, or currying in the usual loose sense

    The returned closure carries the fixed argument as captured state.

  6. What does the third line of this program print? package main import "fmt" func adder(base int) func(int) int { return func(x int) int { return base + x } } func apply(nums []int, f func(int) int) []int { out := make([]int, 0, len(nums)) for _, n := range nums { out = append(out, f(n)) } return out } func main() { add10 := adder(10) fmt.Println(add10(5), add10(-2)) nums := []int{1, 2, 3} fmt.Println(apply(nums, add10)) fmt.Println(apply(nums, func(n int) int { return n * n })) }

    Answer

    15 8 / [11 12 13] / [1 4 9]

    add10 applies the captured base of ten to each element.

  7. What is the signature of the function a range loop accepts since Go 1.23?

    Answer

    func(yield func(T) bool)

    The producer receives the yield function and stops when it returns false.

  8. What does this program print? package main import "fmt" func Count(n int) func(yield func(int) bool) { return func(yield func(int) bool) { for i := 1; i <= n; i++ { if !yield(i) { return } } } } func main() { sum := 0 for v := range Count(5) { sum += v } fmt.Println("sum:", sum) for v := range Count(100) { if v > 3 { break } fmt.Print(v, " ") } fmt.Println() }

    Answer

    sum: 15 / 1 2 3

    The first loop sums 1 to 5, and the second breaks after printing 1, 2 and 3.

  9. What should a producer do when yield returns false?

    Answer

    Stop and return

    false means the consumer left the loop, so further work would be wasted.

  10. Why are the two counters independent?

    Answer

    Each call of the factory creates a new captured variable

    The state lives in the factory call's frame, captured separately by each pair of closures.

The code on this page was run with go 1.26.10 on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev

Banner image