实现说明
活动部件是函数 newCounter、main。
使用要点
- 跑完文件,输出里会留下标记——
first:、second:、addStep(5):。 - 运行整个文件:
main会依次驱动newCounter。
常见问题
运行「闭包捕获外层变量」会打印什么?
整个文件跑完,输出行以 first:、second:、addStep(5): 这类前缀开头。
签名一览:func newCounter() func() int
核心语句
func newCounter() func() int {
count := 0
return func() int {
count++
return count
}
}
代码示例
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)
}