go closure
2016-05-10 18:03
351 查看
// Go supports anonymous functions,
// which can form closures.
// Anonymous functions are useful when you want to define
// a function inline without having to name it.
package main
import “fmt”
// This function
// we define anonymously in the body of
// returned function closes over the variable
// form a closure.
func intSeq() func() int {
i := 0
return func() int {
i += 1
return i
}
}
func main() {
// which can form closures.
// Anonymous functions are useful when you want to define
// a function inline without having to name it.
package main
import “fmt”
// This function
intSeqreturns another function, which
// we define anonymously in the body of
intSeq. The
// returned function closes over the variable
ito
// form a closure.
func intSeq() func() int {
i := 0
return func() int {
i += 1
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`. nextInt := intSeq() // See the effect of the closure by calling `nextInt` // a few times. fmt.Println(nextInt()) fmt.Println(nextInt()) fmt.Println(nextInt()) // To confirm that the state is unique to that // particular function, create and test a new one. newInts := intSeq() fmt.Println(newInts())
相关文章推荐
- Android Native 绘图方法
- 深入理解PHP之匿名函数
- LUA中的闭包(closure)浅析
- SQLSERVER 中GO的作用详解
- javascript prototype,executing,context,closure
- javascript 面向对象编程 function是方法(函数)
- javascript 面向对象编程 function也是类
- ASP.NET MVC @Helper辅助方法和@functons自定义函数的使用方法
- IIS下PHP连接数据库提示mysql undefined function mysql_connect()
- 浅谈Javascript中Object与Function对象
- JavaScript通过function定义对象并给对象添加toString()方法实例分析
- IE 当eval遇上function的处理
- JavaScript中Object和Function的关系小结
- Javascript 使用function定义构造函数
- javascript Object与Function使用
- JavaScript中的Function函数
- JavaScript中的闭包(Closure)详细介绍
- 使用Function.apply()的参数数组化来提高 JavaScript程序性能的技巧
- javascript下function声明一些小结
- 常用的javascript function代码