closures

一个闭包例子,侵删

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())
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 闭包是自包含的函数代码块,可以在代码中被传递和使用。Swift 中的闭包与 C 和 Objective-C 中的代...
    雨影阅读 729评论 0 2
  • //闭包 这章有的地方不懂orz //“闭包是自包含的函数代码块,可以在代码中被传递和使用。Swift 中的...
    你weixiao的时候很美阅读 272评论 0 1
  • Swift 2.2 我总是觉得 Swift 的语法书有点晦涩。看的不是那么让人理解。说实在话,语法书的闭包我看了好...
    Laughingg阅读 410评论 0 1
  • 时间:2017年4月10日至15日 地点:厦门 人物:爸爸、妈妈和我 D1 抵达 一早出发直到下午四点多才终于抵达...
    睡着了的猫阅读 399评论 0 1
  • 1 端午的前一天夜里,雨水冲刷后的能马路倒映出霓虹的闪烁,我和胡子并排走着,胡子说,她今天真好看和我当时梦见的一样...
    北苏阅读 525评论 2 3