Closures

A function inside a function remembers the variables around it. That is state without an object.

A function is a value. You can declare it inside another function, and it will see the surrounding variables:

func Adder(start int) func(int) int {
    sum := start
    return func(v int) int {
        sum += v
        return sum
    }
}

The call add := Adder(10) creates its own sum. Then add(1) returns 11, and the next add(2) returns 13. The state lives as long as the returned function lives. A second call to Adder gets a different sum: the closures do not share it.

A closure captures the variable, not a copy of the value at creation time, unless you yourself copied it into a new local. That is why a loop and a closure were a source of bugs for so long. Since Go 1.22 the loop variable is already new on each iteration, but the rule is wider than the loop: if several functions close over one variable, they see its changes.

Closures are good for short local behavior: a handler, a comparator, a deferred function in defer. They are bad as a hidden global variable. If a closure lives a long time, moves to another goroutine, and mutates outer data, you have shared memory. The same rules apply as to any shared state: either nobody else writes it, or you protect it.

How to read someone else's closure

Find which outer names it reads and writes. If the list is empty, it is simply a function declared nearby. If there is a counter, a buffer, or err, that is state, and it should have a clear owner.

Practice

  1. What is captured

    Two functions were created by two calls to Adder(10). Do they share one and the same sum accumulator?

    • Yes, Adder stores the sum in the package
    • No, each call to Adder has its own sum variable
    • Yes, but only if start matched
    • No, closures are forbidden in Go
  2. An accumulator

    Write Adder(start int) func(int) int. The returned function adds its argument to an inner sum that starts at start, and returns the new sum. Repeated calls of the same function keep accumulating.

  3. A shared variable

    What will the program print? Write the digits with no separator.

    n := 0
    inc := func() { n++ }
    inc()
    inc()
    fmt.Print(n)