Python-Style Generators in Go
In Go, goroutines can be utilized like Python generators, as exemplified in Question 66 of the Tour of Go. The provided code rewrites Question 66 in a simplified manner:
package main import "fmt" func fibonacci(c chan int) { x, y := 1, 1 for { c <- x x, y = y, x + y } } func main() { c := make(chan int) go fibonacci(c) for i := 0; i < 10; i++ { fmt.Println(<-c) } }
Analysis
Alternative Approach
To address these issues, consider the following code:
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) } }
In this example:
The above is the detailed content of Can Go Channels Mimic Python Generators?. For more information, please follow other related articles on the PHP Chinese website!