func main(){
count := make_counter()
for i:=0; i<5; i++ {
fmt.Printf("%v\n",count(i))
}
}
func make_counter()(func(int) int){
local_count := 0
return func(x int) int{
local_count += x
return local_count
}
}
输出如下:
0
1
3
6
10
这是go中使用闭包的例子,make_counter() 返回了一个计算总量的函数,在main方法中循环调用,会发现 local_count
会持续增加而不会重置。
可以认为make_counter() 返回的是一个由引用环境与函数代码组合的 实体
。
资料来源于两篇blog,感谢:
https://www.ibm.com/developerworks/cn/linux/l-cn-closure/index.html
https://www.cnblogs.com/yjf512/archive/2012/12/09/2810313.html