Go基础 专题
专题目录
您的位置:go > Go基础 专题 > Go闭包(匿名函数)实例
Go闭包(匿名函数)实例
作者:--    发布时间:2019-11-20

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

所有的示例代码,都放在 f:\worksp\golang 目录下。安装go编程环境请参考:http://www.h3.com/go/go_environment.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
2
3
1

网站声明:
本站部分内容来自网络,如您发现本站内容
侵害到您的利益,请联系本站管理员处理。
联系站长
373515719@qq.com
关于本站:
编程参考手册