JuniorTheoryCommonNot answered yet
What is a closure in Go, and how does it relate to variables in its enclosing scope?
A closure is a function value that captures variables from its enclosing scope by reference — it refers to the real variable, not a copy. It can read and modify them, and they live as long as the closure does, even after the enclosing function returns.
- ✗Believing the closure captures variables by value, taking a snapshot at creation instead of referencing the live variable
- ✗Assuming a captured local dies when the enclosing function returns, rather than living as long as the closure
- ✗Confusing a closure with a plain anonymous function that has no access to the enclosing scope
- →How does Go keep a captured variable alive after its function returns?
- →What happens if two closures capture the same enclosing variable?
What is a closure in Go?
A closure is a function value that uses variables declared outside its body, in the enclosing scope. The crucial point: it captures those variables by reference, not by copying their value.
func makeAdder() func(int) int {
sum := 0
return func(x int) int {
sum += x // reads and modifies the same sum
return sum
}
}
The returned function refers to the very same sum variable. As a result:
has returned (the compiler moves it to the heap).
- the closure can both read and modify the captured variable;
- the variable lives as long as the closure does — even after
makeAdder
This is exactly how a returned function keeps state between calls.