闭包中的变量为什么不会被遗忘?

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

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 &quot;fmt&quot;

// 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 &lt; 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

firstsecondfibonacci()函数中的变量,它们被返回的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.

huangapple
  • 本文由 发表于 2016年3月31日 03:38:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/36318171.html
匿名

发表评论

匿名网友

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

确定