duanchuaiwan0063 2013-07-24 09:46
浏览 38
已采纳

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>
  • 写回答

1条回答 默认 最新

  • dongpo5207 2013-07-24 10:13
    关注

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)