Go闭包(匿名函数)实例

Go语言支持匿名函数,可以形成闭包。匿名函数在想要定义函数而不必命名时非常有用。

所有的示例代码,都放在 F:\worksp\golang 目录下。安装Go编程环境请参考:/tutorial/detail-5562.html

函数intSeq()返回另一个函数,它在intSeq()函数的主体中匿名定义。返回的函数闭合变量i以形成闭包。
当调用intSeq()函数,将结果(一个函数)分配给nextInt。这个函数捕获它自己的i值,每当调用nextInt时,它的i值将被更新。

通过调用nextInt几次来查看闭包的效果。

要确认状态对于该特定函数是唯一的,请创建并测试一个新函数。

接下来我们来看看函数的最后一个特性是:递归。

closures.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.
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())
}

执行上面代码,将得到以下输出结果 -

F:\worksp\golang>go run closures.go


1

上一篇:Go可变参数的函数实例

下一篇:Go函数递归实例

关注微信小程序
程序员编程王-随时随地学编程

扫描二维码
程序员编程王

扫一扫关注最新编程教程