GO和局部变量中的闭包

This question already has an answer here:

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,

What is the difference between a 'closure' and a 'lambda'?

</div>

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).