Closures in Go


Let’s start with a demo:

func f(i int) func() int {
    return func() int {
        i++
        return i
    }
}
Copy the code

Function f returns a function that is a closure. This function does not define variable I itself, but refers to variable I in its environment (function f).

Let’s look at the effect again:

c1 := f(0)
c2 := f(0)
c1()    // reference to i, i = 0, return 1
c2()    // reference to another i, i = 0, return 1
Copy the code

C1 and c2 refer to different environments, and the same I is not changed when I ++ is called, so the output is 1 both times. Each time f enters, a new environment is formed, and the corresponding closure is the same function, but the environment refers to a different environment.

Variable I is a local variable in function F. It is not possible to assume that this variable is allocated on the stack of function F. Because when f returns, the corresponding stack is invalidated, and the variable I in the function f returns refers to an invalidated location. So variables referenced in the closure’s environment cannot be allocated on the stack.