Sobes.tech
Junior — Middle

What will be executed first in the selection operator: processing data from the channel or reading from the current context?

sobes.tech AI

Answer from AI

In the select statement in Go, the execution order depends on the readiness of channels and other operations. If multiple cases are ready at the same time, a random one is chosen.

Regarding the comparison between handling data from a channel and reading from a context:

  • If there is a case for reading from a channel and a case for reading from a context (for example, <-ctx.Done()), and both are ready, the choice will be random.
  • If only one of them is ready, that one will be executed.

Thus, it is not possible to say definitively which will execute first — it depends on the state of the channels and the context at the moment of executing select.

Example:

select {
case data := <-ch:
    // handle data from channel
case <-ctx.Done():
    // handle context cancellation
}

If both ch and ctx.Done() are ready, the choice will be random.

What will be executed first in the selection… - sobes.tech