闭包 = 函数 + 引用环境
package main
import "fmt"
func getSequence() func() int {
i := 0
return func() int {
i++
return i
}
}
func main() {
f1 := getSequence()
f1()
f1()
fmt.Println(f1())
f2 := getSequence()
fmt.Println(f2())
fmt.Println(f2())
fmt.Println(f1())
}
输出结果为: 3 1 2 4
getSequence返回一个函数,返回的函数就是闭包,闭包函数中没有定义变量,直接引用闭包所在的函数getSequence中的变量i,f1/ f2 通过调用同一个函数getSequence得到不同的引用环境