在匿名函数中的变量生命周期 Golang

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

variable lifecycle in anonymous functions golang

问题

对于你的代码和输出,我来解释一下。

首先,为什么在执行a()两次时,println语句在test函数中只执行了一次呢?这是因为在第一次执行a()时,test函数被调用并返回了一个匿名函数。这个匿名函数被赋值给了变量a。当你再次执行a()时,实际上是在调用这个匿名函数,而不是再次调用test函数。所以println语句只会在第一次调用test函数时执行一次。

其次,为什么匿名函数中的num不会重置为零,而父作用域中的num是零呢?这是因为匿名函数中的num变量是一个闭包变量。闭包是指一个函数捕获并存储了其所在作用域中的变量的引用。在这种情况下,匿名函数捕获了test函数中的num变量的引用。每次调用匿名函数时,它都会使用捕获的引用来访问和修改num变量的值。因此,num的值在每次调用匿名函数时都会增加,并且不会重置为零。

希望这能解答你的问题!如果还有其他疑问,请随时提问。

英文:

im sorry if my question may has obvious or easy answer but i really cant undesrstand what is going on.
this is my code:

import "fmt"

func main() {
    a := test()
    a()
    a()
}

func test() func() {
    num := 0
    fmt.Println("num in test function", num)
    return func() {
	    fmt.Println("num in anonymous function", num)
	    num++
	    fmt.Printf("square is %v: \n", num*num)
	    fmt.Println("=====---====")
    }
}

and this is my output:

num in test function 0
num in anonymous function 0
square is 1:
=====---====
num in anonymous function 1
square is 4:
=====---====`

first why println num in test function execute just one time while i execute a() twice?
and why num in the anonymous function doesnt reset to zero while the num in parent scope is zero?

答案1

得分: 1

当你调用a := test()时,你初始化了a匿名函数内部的num变量,并打印了num in test function 0

然后,a只是你的test()方法的结果,所以当你执行a()时,不会调用你的第一个打印语句。
同样地,num := 0不再被调用。因此,在每次调用a()时,a内部分配的局部变量num将被递增。

英文:

When you call a := test() you initialize num variable inside a anonymous fonction and print num in test function 0.

Then, a is only the result of your test() method, so you will not call your first print when you execute a().
On the same way, num := 0 is not called anymore. So the local variable num assigned inside a will just be incremented on each call of a().

huangapple
  • 本文由 发表于 2023年3月25日 16:50:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/75840582.html
匿名

发表评论

匿名网友

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

确定