英文:
Why are variables in closure not forgotten?
问题
以下是代码的中文翻译:
package main
import "fmt"
// fibonacci 是一个返回一个返回 int 的函数。
func fibonacci() func() int {
first, second := 0, 1
return func() int {
// 在这里返回下一个斐波那契数。
first, second = second, first+second
return first
}
}
func main() {
f := fibonacci()
for i := 0; i < 10; i++ {
fmt.Println(f())
}
}
这段代码返回斐波那契数列的前10个数字。让我感到困惑的是为什么它能够工作。似乎变量 first 和 second 在内存中被保存,因为每次执行代码时,都会返回与前一个斐波那契数列相邻的新数字。我原以为函数在执行完毕后会丢失它们记住的变量。这里到底发生了什么?
英文:
The following code:
package main
import "fmt"
// fibonacci is a function that returns
// a function that returns an int.
func fibonacci() func() int {
first, second := 0, 1
return func() int {
// return next fibonacci number here.
first, second = second, first+second
return first
}
}
func main() {
f := fibonacci()
for i := 0; i < 10; i++ {
fmt.Println(f())
}
}
returns 10 numbers of the fibonacci sequence. What's confusing to me is why is works. It seems like the values first and second are somehow saved in memory, since each time the code is executed, a new fibonacci number in sequence with the previous one is returned. I thought that functions lost their remembered variables when they were done executing. What is going on here?
答案1
得分: 1
first
和second
是fibonacci()
函数中的变量,它们被返回的func() int
所"闭合",该函数是从fibonacci()
返回的。
因此,它们位于与f
相关联的闭包中,只要f
存在,f
就可以访问这些变量。
请参考这个 Go Tour幻灯片(以及其周围的幻灯片)来了解Go闭包的一些解释。
英文:
first
, and second
are variables in the fibonacci()
func, that were 'closed over' by the returned func() int
that was returned from fibonacci()
.
So they are in the closure associated with f
, so f
has access to those variables as long as it exists.
See this Go Tour slide (and the ones around it) for some explanation of Go closures.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论