Closure Counters Capture Outer Variables
Return functions that capture outer variables: each counter keeps independent state, and assignments inside a closure mutate the captured variable itself.
Code
package main
import "fmt"
// newCounter returns a closure that captures the count variable.
func newCounter() func() int {
count := 0
return func() int {
count++
return count
}
}
func main() {
first := newCounter()
second := newCounter()
// 两个闭包各自持有独立的 count 状态
fmt.Println("first:", first(), first(), first())
fmt.Println("second:", second(), second())
// 捕获的是变量本身:闭包里修改,外部读得到
step := 10
addStep := func(x int) int {
step += x
return step
}
fmt.Println("addStep(5):", addStep(5), "step now:", step)
}How it works
Closure Counters Capture Outer Variables is built around the functions newCounter and main.
What to watch for
- The environment needs no preparation beyond having the interpreter or compiler.
Putting it to use
The signature to know first is func newCounter() func() int
The run emits 3 labeled sections — first:, second:, addStep(5): — one per step.
There are 1 call inside main — newCounter — executed top to bottom.
The core lines of the flow
func newCounter() func() int {
count := 0
return func() int {
count++
return count
}
}
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- What does Closure Counters Capture Outer Variables print when run?
- Execute the whole file; each printed line is prefixed with a label like `first:`, `second:`, `addStep(5):`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.