dongnong3019 2013-11-13 15:12
浏览 23
已采纳

去闭包变量范围

I'm reading 'CreateSpace An Introduction to Programming in Go 2012'

and on page 86 I found this evil magic

func makeEvenGenerator() func() uint {
    i := uint(0)

    return func() (ret uint) {
        ret = i
        i += 2
        return
    }
}

// here's how it's called
nextEven := makeEvenGenerator()
fmt.Println(nextEven())
fmt.Println(nextEven())
fmt.Println(nextEven())

1) Why is i not resetting ? 2) is nextEven() returning and uint or is Println so smart that it can work with everything ?

  • 写回答

3条回答 默认 最新

  • dougu4027 2013-11-13 15:36
    关注

    For the sake of clarity, I'll assign names to both functions:

    func makeEvenGenerator() func() uint { // call this "the factory"
        i := uint(0)
    
        return func() (ret uint) { // call this "the closure"
            ret = i
            i += 2
            return
        }
    }
    

    The factory returns the closure – functions are first class citizens in Go i.e. they can be right-hand expressions, for example:

    f := func() { fmt.Println("f was called"); }
    
    f() // prints "f was called"
    

    In your code, the closure wraps over the context of the factory, this is called lexical scoping. This is why the variable i is available inside the closure, not as a copy but as a reference to i itself.

    The closure uses a named return value called ret. What this means is that inside the closure you'll have implicitly declared ret and at the point of return, whatever value ret has will be returned.

    This line:

    ret = i
    

    will assign the current value of i to ref. It will not change i. However, this line:

    i += 2
    

    will change the value of i for the next time the closure is called.


    Here you'll find a little closure example I wrote together for you. It's not extremely useful but illustrates the scope, purpose and use of closures pretty well in my opinion:

    package main
    
    import "fmt"
    
    func makeIterator(s []string) func() func() string {
        i := 0
        return func() func() string {
            if i == len(s) {
                return nil
            }
            j := i
            i++
            return func() string {
                return s[j]
            }
        }
    }
    
    func main() {
    
        i := makeIterator([]string{"hello", "world", "this", "is", "dog"})
    
        for c := i(); c != nil; c = i() {
            fmt.Println(c())
        }
    
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 2024-五一综合模拟赛
  • ¥15 如何将下列的“无限压缩存储器”设计出来
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口