Closure in GO and local variables

This question already has an answer here:

  • What is the difference between a 'closure' and a 'lambda'? 10 answers

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

    链接地址: http://www.djcxy.com/p/51274.html

    上一篇: 封闭和lambda之间的区别?

    下一篇: 在GO和局部变量中关闭