我在围棋来到后关闭的例子在这里: https://gobyexample.com/closures去重新封闭的可变
它给围棋封闭作用域的一个非常直接的例子。我改变了我是如何从“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是否变量 'i' 的在intSeq()不获取重新分配每次nextInt()在主()被调用?
同意。尽管我想对此表示赞赏,但这在技术上不是问题的答案,所以我必须坚持积极的评论;) – RayfenWindspear