Sobes.tech
Junior — Middle

How is the order of execution of case conditions in a select statement determined?

sobes.tech AI

Answer from AI

In the select statement in Go, the order of checking case conditions is not guaranteed and is random when multiple channels are ready.

This means that if several channels are ready for an operation (such as reading or writing), Go randomly chooses one of them to execute, to avoid prioritization and blocking.

Example:

select {
case msg1 := <-chan1:
    fmt.Println("Received from chan1", msg1)
case msg2 := <-chan2:
    fmt.Println("Received from chan2", msg2)
default:
    fmt.Println("No channel ready")
}

If both channels chan1 and chan2 are ready, Go will choose a random case.

If no channels are ready and there is a default, the default will execute.

Thus, the order of case in the code does not affect the choice, which helps avoid blocking and ensures fairness when handling multiple channels.

How is the order of execution of case conditions in a… - sobes.tech