package main
import "fmt"
//构造闭包
// This function `intSeq` returns another function, which
// we define anonymously in the body of `intSeq`. The
// returned function _closes over_ the variable `i` to
// form a closure.
//这个函数`intSeq`返回另一个函数,
//我们在`intSeq`的主体中匿名定义。
//返回的函数_closes变量`i`形成一个闭包。
func intSeq() func() int {
i := 0
return func() int {
i++
return i
}
}
func main() {
// We call `intSeq`, assigning the result (a function) to `nextInt`.
// This function value captures its own `i` value,
// which will be updated each time we call `nextInt`.
//我们调用`intSeq`,将结果(函数)赋给`nextInt`。
//此函数值捕获自己的`i`值,每次调用`nextInt`时都会更新。
nextInt := intSeq() //生成闭包
// To confirm that the state is unique to that particular function,
// create and test a new one.
// 通过几次调用`nextInt`来查看闭包的效果。
fmt.Println(nextInt()) //1
fmt.Println(nextInt()) //2
fmt.Println(nextInt()) // 3
// See the effect of the closure by calling `nextInt` a few times.
// 要确认该状态对于该特定函数是唯一的,请创建并测试一个新函数。
newInts := intSeq() //创建新闭包环境
fmt.Println(newInts()) //1,i从1开始
}
总结:闭包就是一个函数引用另外一个函数的变量,因为变量被引用着所以不会被回收,因此可以用来封装一个私有变量。这是优点也是缺点,不必要的闭包只会徒增内存消耗!另外使用闭包也要注意变量的值是否符合你的要求,因为他就像一个静态私有变量一样。