Capture variables with Go closures
Capture variables with Go closures
A closure is a function value that can refer to variables from its enclosing function. It captures the variable, not a frozen copy of its value. The captured variable remains accessible for as long as it is needed by reachable closures.
package main
import ( "fmt")
func main() { n := 1 read := func() int { return n } n = 4 fmt.Println(read())}The function literal has no name; read holds its function value. When called later it reads the current value of n, which is now 4. Use a separate variable initialized with a copy if you need a snapshot of a simple value.
Expected output:
4Independent counters
package main
import ( "fmt")
func counter() func() int { n := 0; return func() int { n++; return n } }func main() { a := counter() b := counter() fmt.Println(a(), a(), b())}Each invocation of counter creates its own n. Calls to a update one variable while b updates another. Returning the function is safe after the factory returns. This example is sequential; concurrent access to the same mutable captured variable requires synchronization, covered later.
Expected output:
1 2 1Try it locally
Write a function makeAdder(base int) func(int) int that returns a closure adding base to its argument. Create add5 and apply it to 2 and 10.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Scope and closures 03: Capture variables with Go closures
Check the lesson objective before moving on.
What does the read closure return after n changes from 1 to 4?
Why do two calls to counter create independent counters?