When I'm running the following simple code it prints "ping" as expected:
messages := make(chan string)
go func() { messages <- "ping" }()
fmt.Println(<-messages)
However, when I'm using the same non-buffered channel with select, it's not fulfilling it with a ping, thus printing "no message sent":
messages := make(chan string)
select {
case messages <- "ping":
fmt.Println("sent message")
default:
fmt.Println("no message sent")
}
Why this is happening? The channels are the same, but it's accessible with goroutine but not with select.
In addition, I've found out that when I'm converting it to a buffered channel (with size 1) it fulfills the channel like a charm: Why?
messages := make(chan string,1)
select {
case messages <- "ping":
fmt.Println("sent message")
default:
fmt.Println("no message sent")
}
Note nothing is hanging up, but just immediately returns as I've described.