This is a created article in which the information may have evolved or changed.
In the programming language you've been exposed to, more or less has been exposed to closures.
So what's a closure?
Closures contain variables that are free (not bound to specific objects), are not defined within this block of code or in any global context, but are defined in the context in which the code block is defined (local variables). The word "closure" derives from the combination of the following: the code block to be executed (since free variables are contained in the code block, these free variables and the objects they refer to are not freed) and the computing Environment (scope) that provides the binding for free variables--from Baidu
Closures in the Golang
Implementing closures in Golang is a very simple thing, such as:
Let's analyze this closure, the function closure () is a function that does not need parameters, returns a type func (int) int type, in main (), we use a to receive the closure returned by the closure, which is equivalent to A is a func ( int) a function of type int, call a (5) on a, return the result with an X variable to receive, and then print the result.
If you have some memory of C, then you know that this notation in the closure () function is not allowed, because C is inside the function, the memory allocation is allocated on the stack, and the function closure () returns after this part of the stack space is invalidated; but in the go language, it works. Let's try to analyze why.
Follow GDB to see what the results are:
Use the command go build-gcflags "-n-l-M" closure
One of the closure is the one above the closure of the project, to see what important messages are printed:
What the? &x escapes to Heap??? No wonder we have no problem with the call to a function, Iers variable x flew into the heap, which means that the go language automatically recognizes this and allocates X's memory on the heap instead of on the stack of the function closure.