英文:
Closure in GO and local variables
问题
我在http://en.wikipedia.org/wiki/Closure_(computer_science)找到了以下定义:
在编程语言中,闭包(也称为词法闭包或函数闭包)是一个函数或对函数的引用,以及一个引用环境 - 一个存储该函数的每个非局部变量的引用的表(也称为自由变量或上值)。与普通函数指针不同,闭包允许函数在其直接词法范围之外被调用时访问这些非局部变量。
这是所有情况都是真的吗?不能lambda函数(创建闭包的函数)继续引用在lambda被调用时超出范围的局部变量吗?这不是GO的行为吗?
PS:我仍然想知道为什么他们使用“lambda”这个术语
关于这个问题,我找到了答案
https://cstheory.stackexchange.com/questions/18443/lambda-term-usage-in-programming
以下帖子可能对其他读者有帮助:
https://stackoverflow.com/questions/220658/what-is-the-difference-between-a-closure-and-a-lambda
英文:
I have found following definition at http://en.wikipedia.org/wiki/Closure_(computer_science)
> In programming languages, a closure (also lexical closure or function
> closure) is a function or reference to a function together with a
> referencing environment—a table storing a reference to each of the
> non-local variables (also called free variables or upvalues) of that
> function.[1] A closure—unlike a plain function pointer—allows a
> function to access those non-local variables even when invoked outside
> of its immediate lexical scope.
is it true all occasions ? can't lambda functions (those creates a closure) keep refereeing to local variable that would be in out of scope when the lambda is called? isn't this is the behavior of GO?
PS: I am still wondering why they use "lambda" term
For this got the answer
https://cstheory.stackexchange.com/questions/18443/lambda-term-usage-in-programming
Following post might find helpful for other readers,
https://stackoverflow.com/questions/220658/what-is-the-difference-between-a-closure-and-a-lambda
答案1
得分: 7
引用Go语言规范:
函数字面量
函数字面量表示一个匿名函数。
FunctionLit = "func" Function .
func(a, b int, z float64) bool { return a*b < int(z) }
函数字面量可以赋值给一个变量或直接调用。
f := func(x, y int) int { return x + y }
func(ch chan int) { ch <- ACK }(replyChan)
函数字面量是闭包:它们可以引用在外部函数中定义的变量。这些变量在外部函数和函数字面量之间共享,并且只要它们可访问,就会一直存在。
所以,在Go语言中,闭包可以保证访问在函数字面量定义的作用域中可见的任何变量。Go编译器会识别在作用域中“捕获”的变量,并将它们强制放到堆上,而不是定义上下文的堆栈中(如果有的话 - 也可以有顶级声明的闭包)。
英文:
Quoting the Go language specification:
> Function literals
>
> A function literal represents an anonymous function.
FunctionLit = "func" Function .
func(a, b int, z float64) bool { return a*b < int(z) }
> A function literal can be assigned to a variable or invoked directly.
f := func(x, y int) int { return x + y }
func(ch chan int) { ch <- ACK }(replyChan)
>Function literals are closures: they may refer to variables defined in a surrounding function. Those variables are then shared between the surrounding function and the function literal, and they survive as long as they are accessible.
So yes, in Go the closure is guaranteed to have access to any variable visible in the scope where the function literal was defined. The Go compiler recognizes variables "captured" in a scope and forces them to the heap instead of the defining context stack (if any - there can be also TLD [top level declaration] closures).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论