This is a modified version of the one provided by "A Tour of Go".
package main
import "fmt"
func fibonacci(c, quit chan int) {
x, y := 0, 1
for {
select {
case c <- x:
x, y = y, x+y
fmt.Println("GEN", x)
case <-quit:
fmt.Println("quit")
return
}
}
}
func main() {
c := make(chan int)
quit := make(chan int)
go func() {
for i := 0; i < 10; i++ {
fmt.Println("DISP", <-c)
}
quit <- 0
}()
fibonacci(c, quit)
}
Here is the output for the above code:
DISP 0
GEN 1
GEN 1
DISP 1
DISP 1
GEN 2
GEN 3
DISP 2
DISP 3
GEN 5
GEN 8
DISP 5
DISP 8
GEN 13
GEN 21
DISP 13
DISP 21
GEN 34
GEN 55
DISP 34
quit
I don't understand the behaviour of the code. Why are 2 Fibonacci numbers generated before displaying both of them? Does this depend on the execution environment?