golang 闭包初探

初次接触闭包的概念。主要看看闭包这种语法的效果,以及我的认识。

如下是一个简单的闭包形式
参数列表为空,返回的是函数指针。

func testClosure() func ()int{

    i := 0
    return func ()int{
        i++
        return i
    }

}

这时候我们去获取返回的值。

    f := testClosure()
    fmt.Printf("f type:%T \n", f)
    for i := 0; i < 10; i++ {
        fmt.Printf("function:%s the %d time called value:%d\n", "testClosure", i, f()) //保存了内部的变量
    }

尝试获取func,打印出类型。接着我们尝试调用该函数10次查看返回的结果。

结果如下

f type:func() int 
function:testClosure the 0 time called value:1
function:testClosure the 1 time called value:2
function:testClosure the 2 time called value:3
function:testClosure the 3 time called value:4
function:testClosure the 4 time called value:5
function:testClosure the 5 time called value:6
function:testClosure the 6 time called value:7
function:testClosure the 7 time called value:8
function:testClosure the 8 time called value:9
function:testClosure the 9 time called value:10

为什么 i的值能够累加?

返回的func如果把它类比成一个类或者是结构体。它本身包含了一个变量i。那么,只要这个类不释放掉,则里面的变量也是不会释放掉的。函数 + 变量作为一个整体 形成了闭包。

闭包的用法

  • 这种写法的经常用在全局环境中,可以避免添加太多的全局变量和全局函数,特别是多人合作开发的时候,可以减少因此产生的命名冲突等,避免污染全局环境。
  • 闭包给访问外部函数定义的内部变量创造了条件。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值