I recently started with go and I am really confused about the order of execution of this program. I hope I am not asking really trivial questions here.
This is basically #69 in the golang tour, with some Println I have inserted; Link to playground: http://play.golang.org/p/PXDlD3EA2f
func fibonacci(c, quit chan int) {
x, y := 0, 1
fmt.Println("Inside the fibonacci")
for {
select {
case c <- x:
fmt.Println("Inside the for, first case, before reassigning ", x, y)
x, y = y, x+y
fmt.Println("Inside the for, first case, after reassigning ", x, y)
case <-quit:
fmt.Println("quit")
return
}
}
}
func main() {
fmt.Println("Begin of Main")
c := make(chan int)
quit := make(chan int)
fmt.Println("Before gonig to the func")
go func() {
fmt.Println("Inside go routine")
fmt.Println("Inside go routine... again")
for i := 0; i < 10; i++ {
fmt.Println("Inside go routine and the for, before printing the channel")
fmt.Println(<-c)
}
quit <- 0
}()
fmt.Println("Before calling to fibonacci")
fibonacci(c, quit)
fmt.Println("Closing")
}
In the very verbose output I obtain (see attached image below), there are a couple of things I do not understand:
why is the "Inside the fibonacci" line before the ones in the go routine? Is this because after the go command, the compiler is just reading at the same time inside func and fibonacci?
how do fibonacci and func interact? func is not changing the channel c, so why is fibonacci reacting? Who's changing c?
why inside fibonacci there are 5 prints together every time? Honesty I was expecting only 2.
Output of the function: