closures _ golang

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"
)

func intSeq() func() int {
    i := 0
    return func() int {
        i += 1
        return i
    }
}

func main() {

    nextInt := intSeq()

    fmt.Println(nextInt())
    fmt.Println(nextInt())
    fmt.Println(nextInt())

    nextInts := intSeq()
    fmt.Println(nextInts())
}
1
2
3
1

总结 :

  1 : 匿名函数内部的值不是暴露在外面的....

posted on 2015-03-14 17:28  xjk112  阅读(171)  评论(0编辑  收藏  举报