I'm trying to understand the behaviour of the write to channel operation in the first select in the code below:
func main() {
ch := make(chan int)
select {
case ch <- 42:
fmt.Println("Sent value to channel")
default:
fmt.Println("Channel is not ready for sending")
}
select {
case value := <-ch:
fmt.Println("Received value from channel:", value)
default:
fmt.Println("Channel is not ready for receiving")
}
}
Does the write ch <- 42
get completed and then since there is no other goroutine to read it, the default is selected? Or, the write is never attempted since there is no goroutine to read it and default is selected?
When select
statement runs, it checks to see which cases can run, and selects one randomly. If none are available to run and a default is present, default case is selected.
So in your first select statement, the channel send operation cannot run, because the channel is not buffered and there are no goroutines waiting to receive the value. Because of that, default
case is selected. Similarly for the second select
, because the receive operation cannot be performed.