I'm a new Go learner, and I'm following gobyexample.com to learn the basics. When I reach the "closing channels" section, the tutorial inserts this code snippet (I'll remove original comments):
package main
import "fmt"
func main() {
jobs := make(chan int, 5)
done := make(chan bool)
go func() {
for {
j, more := <-jobs
if more {
fmt.Println("received job", j)
} else {
fmt.Println("received all jobs")
done <- true
return
}
}
}()
for j := 1; j <= 18; j++ {
jobs <- j
fmt.Println("sent job", j)
}
close(jobs)
fmt.Println("sent all jobs")
<-done
}
The original code was setting a 3 instead of a 18 in the job sender loop.
Executing this code in play.golang.org it is what I don't fully understand. It always outputs the following:
sent job 1
sent job 2
sent job 3
sent job 4
sent job 5
received job 1
received job 2
received job 3
received job 4
received job 5
received job 6
sent job 6
sent job 7
sent job 8
sent job 9
sent job 10
sent job 11
sent job 12
received job 7
received job 8
received job 9
received job 10
received job 11
received job 12
received job 13
sent job 13
sent job 14
sent job 15
sent job 16
sent job 17
sent job 18
sent all jobs
received job 14
received job 15
received job 16
received job 17
received job 18
received all jobs
So I understand that the "queue" of a channel (I'm aware this terminology is not the most accurate, but for the purpose of learning myself it is what I understand about what a channel is) is of size 5 so the first 10 log messages are fine for me.
But how can be the message 6 and 13 be output their reception prior than their actual sending? How can be 7 messages sent in a row, if the channel size is 5? What am I missing from this?