Python-style generators in Go

后端 未结 4 2081
梦谈多话
梦谈多话 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:40

    Yes, increasing the buffer size might drastically increase the execution speed of your program, because it will reduce the number of context switches. Goroutines aren't garbage-collected, but channels are. In your example, the fibonacci goroutine will run forever (waiting for another goroutine to read from the channel c), and the channel c will never be destroyed, because the fib-goroutine is still using it.

    Here is another, sightly different program, which do not lack memory and is imho more similar to Python's generators:

    package main
    
    import "fmt"
    
    func fib(n int) chan int {
        c := make(chan int)
        go func() {
            x, y := 0, 1
            for i := 0; i <= n; i++ {
                c <- x
                x, y = y, x+y
            }
            close(c)
        }()
        return c
    }
    
    func main() {
        for i := range fib(10) {
            fmt.Println(i)
        }
    }
    

    Alternatively, if you do not know how many Fibonacci numbers you want to generate, you have to use another quit channel so that you can send the generator goroutine a signal when it should stop. This is whats explained in golang's tutorial https://tour.golang.org/concurrency/4.

提交回复
热议问题