初次接触闭包的概念。主要看看闭包这种语法的效果,以及我的认识。
如下是一个简单的闭包形式
参数列表为空,返回的是函数指针。
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
返回的func如果把它类比成一个类或者是结构体。它本身包含了一个变量i。那么,只要这个类不释放掉,则里面的变量也是不会释放掉的。函数 + 变量作为一个整体 形成了闭包。
- 这种写法的经常用在全局环境中,可以避免添加太多的全局变量和全局函数,特别是多人合作开发的时候,可以减少因此产生的命名冲突等,避免污染全局环境。
- 闭包给访问外部函数定义的内部变量创造了条件。
文章来源: golang 闭包初探