I am very new to golang. I get very confused when testing how channel works in Golang today.
According to the tutorial:
Sends to a buffered channel block only when the buffer is full. Receives block when the buffer is empty.
My test program looks like this:
package main
import "fmt"
func main() {
ch := make(chan int, 2)
go func(ch chan int) int {
for i := 0; i < 10; i++ {
fmt.Println("goroutine: GET ", <-ch)
}
return 1
}(ch)
for j := 0; j < 10; j++ {
ch <- j
fmt.Println("PUT into channel", j)
}
}
I get the output like this:
PUT into channel 0
PUT into channel 1
goroutine: GET 0
goroutine: GET 1
goroutine: GET 2
PUT into channel 2
PUT into channel 3
PUT into channel 4
PUT into channel 5
goroutine: GET 3
goroutine: GET 4
goroutine: GET 5
goroutine: GET 6
PUT into channel 6
PUT into channel 7
PUT into channel 8
PUT into channel 9
Notice that number 2 is fetched from the channel before even been put in the channel. why does this happen?