Python-style generators in Go

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

    Using channels to emulate Python generators kind of works, but they introduce concurrency where none is needed, and it adds more complication than's probably needed. Here, just keeping the state explicitly is easier to understand, shorter, and almost certainly more efficient. It makes all your questions about buffer sizes and garbage collection moot.

    type fibState struct {
        x, y int
    }
    
    func (f *fibState) Pop() int {
        result := f.x
        f.x, f.y = f.y, f.x + f.y
        return result
    }
    
    func main() {
        fs := &fibState{1, 1}
        for i := 0; i < 10; i++ {
            fmt.Println(fs.Pop())
        }
    }
    

提交回复
热议问题