Unlike variable declarations, Go language cannot declare another function in a function. So in Go's source file, function declarations appear on the outermost layer.
"Declaration" is to associate a type of variable with a name.
Go has function-type variables. In this way, although another function cannot be declared directly in one function, a function-type variable can be declared in one function. The function at this time is called a closure.
example:
packagemain
import"fmt"
funcmain(){
add:=func(baseint)func(int)(int){
returnfunc(iint)(int){
returnbase+i
}
}
add5:=add(5)
("add5(10)=",add5(10))
}
The only useful value of this example is probably to show the construction and use of closures.
add is a closure because it is a variable of the type of a nameless function. It can be considered as a closure workshop, and a closure is returned (produced) according to the entry parameters. In this way, add5 is a closure obtained by using 5 as the parameter of add.
The declaration of the closure is inside another function, forming a nest. Like the nesting of blocks, the inner variable can cover the outer variables of the same name, and the outer variables can be used directly in the inner layer. For example, the base parameter of add is in the outer layer of the closure returned by return, so its value 5 still exists after add is returned and assigned to add5. When add5 is executed, parameter i can be added from the base obtained from this outer layer to obtain the result 15.
Personal understanding:
In fact, the most convenient way to understand closures is to regard the closure function as a class. A closure function call is to instantiate a class.
Then you can see which are "global variables" and which are "local variables" based on the perspective of the class.
For example, the add function in the above example returns func(int) int function
pos and neg instantiate two "closure classes" respectively, and there is a "closure global variable" sum in this "closure class". So this makes it easy to understand the returned result.
Let’s take a look at the following example:
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++ {
(
pos(i),
neg(-2*i),
)
}
}
Run returns the 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 in Go, an entity composed of a function and its related reference environment.