【发布时间】:2018-01-24 23:56:02
【问题描述】:
我在这里遇到了 Go 中的一个闭包示例: https://gobyexample.com/closures
它给出了 Go 中闭包作用域的一个非常直接的示例。我将 i 的初始化方式从“i := 0”更改为“i := *new(int)”。
func intSeq() func() int {
i := *new(int)
return func() int {
i += 1
return i
}
}
func main() {
// We call `intSeq`, assigning the result (a function)
// to `nextInt`. This function value captures its
// own `i` value, which will be updated each time
// we call `nextInt`.
nextInt := intSeq()
// See the effect of the closure by calling `nextInt`
// a few times.
fmt.Println(nextInt())
fmt.Println(nextInt())
fmt.Println(nextInt())
// To confirm that the state is unique to that
// particular function, create and test a new one.
newInts := intSeq()
fmt.Println(newInts())
}
这个输出仍然是 1,2,3,1。是否每次调用 main() 中的 nextInt() 时都不会重新分配 intSeq() 中的变量“i”?
【问题讨论】:
标签: go closures anonymous-function