Go函数之闭包

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开始
}

总结:闭包就是一个函数引用另外一个函数的变量,因为变量被引用着所以不会被回收,因此可以用来封装一个私有变量。这是优点也是缺点,不必要的闭包只会徒增内存消耗!另外使用闭包也要注意变量的值是否符合你的要求,因为他就像一个静态私有变量一样。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值