I don't understand how the Done()
channel in context.Context
can work as intended. The module documentation (and source code using it) relies on this pattern:
select {
case <-ctx.Done():
return ctx.Err()
case results <- result:
}
The channel return by Done()
is closed if the Context
is canceled or timed out, and the Err()
variable holds the reason.
I have two questions regarding this approach:
What's the behavior of
select
when a channel is closed? When and why is the case entered? Does the fact that there's no assignment have relevance?According to the language reference:
If one or more of the communications can proceed, a single one that can proceed is chosen via a uniform pseudo-random selection.
If the choice is random, how does that pattern guarantee that I won't be sending results down a pipeline when the
Context
is canceled? I would understand if the cases were evaluated in declaration order (and closed channel cases were selected).
If I'm completely off the track here, please explain this to me from a better angle.