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.

GoData Integrity

Code

gosnippet
29 lines
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

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):`.