新学习者 Golang。为什么我的局部变量在函数调用之间被保存?

huangapple go评论86阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2022年11月8日 00:44:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/74350011.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定