美文网首页
gobyexample-closures

gobyexample-closures

作者: bocsoft | 来源:发表于2018-11-07 09:54 被阅读0次

来源:https://github.com/xg-wang/gobyexample/tree/master/examples

// Go 支持 [_匿名函数_],并能用其构造闭包。
//匿名函数在你想定义一个不要命名的内联函数时很实用
package main

import "fmt"

//此函数返回另一个在函数体内定义的匿名函数。这个函数使用闭包的方式_隐藏_变量`i`
func intSeq() func() int {
    i := 0
    return func() int {
        i++
        return i
    }
}

func main() {
    nextInt := intSeq()

    //该返回的函数,每次调用时都会更新自己的`i`的值,达到闭包的效果
    fmt.Println(nextInt()) //1
    fmt.Println(nextInt()) //2
    fmt.Println(nextInt()) //3

    //其状态对于特定的函数是唯一的
    newInts := intSeq()
    fmt.Println(newInts()) //1
}

输出结果:

1
2
3
1

相关文章

网友评论

      本文标题:gobyexample-closures

      本文链接:https://www.haomeiwen.com/subject/ccymxqtx.html