英文:
New learner Golang. Why does my local variable saved between call?
问题
我有一个关于局部变量 "i" 的问题。第二次调用 nextEven 时,我认为 "i" 应该重新初始化为 0。但是值 "i" 被保存在 "makeEvengenerator()" 中。
package main
import "fmt"
func makeEvengenerator() func() int {
i := 0
return func() (ret int) {
ret = i
i += 2
return ret
}
}
func main() {
nextEven := makeEvengenerator()
fmt.Println(nextEven())
fmt.Println(nextEven())
fmt.Println(nextEven())
}
我期望输出为 0 0 0。
另外,我不明白为什么每次调用 nextEven() 时,代码 "i := 0" 没有再次运行。
英文:
I have a problem with local variable "i". The second time i call nextEven, i think "i" should be intitialized back to 0. But the value "i" is saved in "makeEvengenerator()".
package main
import "fmt"
func makeEvengenerator() func() int {
i:=0
return func() (ret int) {
ret = i
i += 2
return ret
}
}
func main() {
nextEven := makeEvengenerator()
fmt.Println(nextEven())
fmt.Println(nextEven())
fmt.Println(nextEven())
}
I expected in to print out 0 0 0
Also I dont understand why everytime I call nextEven(), the code "i:=0" dont run again everytime i call the nextEven()
答案1
得分: 2
第二次调用nextEven
时,我认为"i"应该重新初始化为0。
为什么会这样呢?如果你真的想将其重新初始化为0,你可以这样做:
func makeEvenGenerator() func() int {
return func() (ret int) {
i := 0
ret = i
i += 2
return ret
}
}
但这样做没有太多意义,因为通常你希望闭包封装一个状态或依赖项。
你可以在这里找到一些文档和其他示例。
英文:
> The second time i call nextEven, i think "i" should be intitialized back to 0
Why would it ? If you really want to reinitialize 0, then you can do:
func makeEvengenerator() func() int {
return func() (ret int) {
i := 0
ret = i
i += 2
return ret
}
}
But it would not make much sense as you usually want a closure to encapsulate a state or dependencies.
You can get some documentation and alternate examples here.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论