The closure is an anonymous function. It can access variables declared outside the function and retain the current value between different function calls.
The following example shows the use of functions as return values.
We can see that in multiple calls, the value of the variable x is retained, that is, 0+1=1, then 1+10=11, and finally 11+100=111.
The closure function saves and accumulates the variable values in it, regardless of whether the external function exits, you can continue to operate the local variables in the external function.
The following is a complete code example.
package main
import "fmt"
func main() {
var f = adder()
fmt.Println(f(1))
fmt.Println(f(10))
fmt.Println(f(100))
}
func adder() func(int) int {
x := 0
return func(delta int) int {
fmt.Printf("%d + %d = %d\n", x, delta, x+delta)
x += delta
return x
}
}
Below is the program output:
0 + 1 = 1
1
1 + 10 = 11
11
11 + 100 = 111
111