Unlike the declaration of a variable, the go language cannot declare another function in a function. So in the go source file, the function declaration appears on the outermost layer.
"Declaration" is to associate a type of variable with a name.
In go there are variables of the function type, so that although you cannot declare another function directly in one function, you can declare a variable of a function type in a function, at which point the function is called a closure (closure).
Cases:
Copy Code code as follows:
Packagemain
Import "FMT"
Funcmain () {
Add:=func (Baseint) func (int) (int) {
Returnfunc (iint) (int) {
Returnbase+i
}
}
Add5:=add (5)
Fmt. Println ("add5 (+) =", Add5 (10))
}
The only use value of this example is probably to demonstrate the construction and usage of closures.
Add is a closure because it is a variable of a nameless function type. It can be considered a closure workshop, which returns (produces) a closure according to the entry parameters. So Add5 is a closure that is obtained using 5 as the parameter of Add.
The closure declaration is nested within another function. As with the nesting of blocks, the inner variables can obscure the outer variables of the same name, and the outer variables can be used directly in the inner layer. If the base parameter of add is the outer layer of the closure returned by return, its value 5 is still present after the add is returned and assigned to ADD5. When ADD5 executes, parameter I can be added from the base of the outer layer, resulting in a result of 15.
Personal Understanding:
In fact, the most convenient way to understand closure is to think of the closure function as a class, and a closure function call is to instantiate a class.
Then you can see from the perspective of the class which is "global variables", which are "local variables".
For example, the Adder function in the previous example returns the function of the func (int) int
Pos and neg have instantiated two "closures", and there is a "closure global variable" sum in the "Closure class". So it's good to understand the results of the return.
Let's look at one of the following examples:
Copy Code code as follows:
Package Main
Import "FMT"
Func adder () func (int) int {
Sum: = 0
return func (x int) int {
sum = X
return sum
}
}
Func Main () {
POS, neg: = Adder (), Adder ()
For I: = 0; I < 10; i++ {
Fmt. Println (
POS (i),
Neg ( -2*i),
)
}
}
Run return Result:
0 0
1-2
3-6
6-12
10-20
15-30 21-42 28-56
36-72
45-90
This is the closure of the go, a function and an entity that is combined with the referencing environment associated with it.