Feature: Closures can maintain their original state between multiple calls
Let's look at an example:
func main() {
adder := makeAdder(10)
fmt.Println(adder(5)) // 输出:15,因为 10 + 5 = 15
fmt.Println(adder(20)) // 输出:30,因为 10 + 20 =30
}
func makeAdder(base int) func(int) int {
return func(num int) int {
return base + num
}
}
In this example, we can func makeAdder(base int) func(int) int
split the function into two parts, namely:
func makeAdder(base int)
func(int) int
The anonymous function func(int) int
acts as makeAdder
the return value of the function.
That is, the makeAdder function receives an integer as a parameter and returns an anonymous function. The returned anonymous function is a closure function because it refers to the variable base in the scope of the makeAdder function, which is the structure definition of the closure function.
In the feature of the closure function, we can see that in the closure function, we first set the value of the variable base to 10.
- In the first operation, add 5 to it, and the resulting value is 15
- Then add 20 to get a value of 30 instead of 20
This means that every time the closure is called, the value inside it is still the initial value. That is, the closure can maintain its original state between multiple calls .