by assbuttbuttass · 4y ago · 0 comments
for ctx.Err() == nil {
select {
case <-ctx.Done():
return nil
case thing := <-thingCh:
// Process thing...
case <-time.After(5*time.Second):
return errors.New("timeout")
}
}
The extra check for ctx.Err before the select statement easily resolves the author's issue.Additionally, this would only work if you had one predominant condition and that condition was context-based. If you have multiple ordered conditions upon which you want to exit, I can't think of how you'd express that as a range.
I guess you're thinking of "what if thingCh and ctx.Done activate simultaneously?"
There's no real difference between happening simultaneously and happening one after another.
As for your other point, you can just write code like
select {
case x := <-conditionA:
return x
default:
}
select {
case x := <-conditionB:
return x
default:
}
...
But I've personally never needed code like this. select {
case a := <-conditionA:
return a
default:
}
select {
case b := <-conditionB:
case a := <-conditionA:
return a
default:
return b
default:
}I've written `select { ..., default: }` enough times I also wish it had shorthand syntax - sometimes it's even clearer to range one "primary" channel and lead the code block with that check - but I cannot think of a case where relying on a deterministic select would not have led to a bug.