上QQ阅读APP看书,第一时间看更新
Closure
A closure is a function that closes over variables in its outer scope. We really need an example to understand that statement! Here's a good one:
func addTwo() func() int {
sum := 0
return func() int { // anonymous function
sum += 2
return sum
}
}
func main() {
twoMore := addTwo()
fmt.Println(twoMore())
fmt.Println(twoMore())
}
You will see the following output:
2
4
The preceding closure is formed by the addTwo function. Inside addTwo, both sum and the anonymous function are declared in the same lexical scope. Since addTwo closes over both sum and the anonymous function, and because sum was declared before the anonymous function, the anonymous function always has access to, and can modify, the sum variable. As soon as addTwo is assigned to twoMore, the addTwo functions's anonymous function gets access to the sum variable and holds on to it as long as the application continues to run.