Python-style generators in Go

后端 未结 4 2083
梦谈多话
梦谈多话 2021-02-01 16:06

I\'m currently working through the Tour of Go, and I thought that goroutines have been used similarly to Python generators, particularly with Question 66. I thought 66 looked co

4条回答
  •  暖寄归人
    2021-02-01 16:28

    You could use closures to simulate a generator. Here is the example from golang.org.

    package main
    
    import "fmt"
    
    // fib returns a function that returns
    // successive Fibonacci numbers.
    func fib() func() int {
        a, b := 0, 1
        return func() int {
            a, b = b, a+b
            return a
        }
    }
    
    func main() {
        f := fib()
        // Function calls are evaluated left-to-right.
        fmt.Println(f(), f(), f(), f(), f())
    }
    

提交回复
热议问题