What is a closure?
Go function can be a closure. A closure is a function value that references a variable outside the function body.(Recommended learning:go)
This function can access and assign values to the referenced variable; in other words, this function is "bound" to this variable superior.
My unreliable understanding is that a closure is equivalent to an instance of a class, and variables outside the function body are equivalent to the variables stored in this instance.
When there is no closure, the function is a one-time transaction. After the function is executed, the value of the variable in the function cannot be changed (the memory should be released);
With the closure The function becomes the value of a variable. As long as the variable is not released, the function will always be alive and exclusive, so the value of the variable in the function can be changed later (because this way the memory will not be reclaimed by Go, which will always cached there).
The main significance of closure
Reduce the scope of variables and reduce the pollution of global variables. If the following accumulation is implemented using global variables, the global variables will be easily contaminated by others.
At the same time, if I want to implement n accumulators, I need n global variables each time.
Using the backpack, each generated accumulator myAdder1, myAdder2 := adder(), adder() has its own independent sum, and sum can be regarded as myAdder1.sum and myAdder2.sum.
Use the backpack to implement functions with their own status!
package main import ( "fmt" ) func adder() func(int) int { sum := 0 return func(x int) int { sum += x return sum } } func main() { myAdder := adder() // 从1加到10 for i := 1; i <= 10; i++ { myAdder(i) } fmt.Println(myAdder(0)) // 再加上45 fmt.Println(myAdder(45)) }
Result:
55// 1+...+10 100
The above is the detailed content of What is the use of golang closure?. For more information, please follow other related articles on the PHP Chinese website!