Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional cases in Go select statement

Tags:

go

I'm trying to write a select in Go that incorporates an optional timeout, something like this:

done := false

for !done {
    if timeout > 0 {
        select {
        case value := <- somechannel:
            // Do something with value
        case <- time.After(timeout):
            done = true
        }
    } else {
        select {
        case value := <- somechannel:
            // Do something with value
        default:
            done = true
        }
    }
}

That is, if nothing is pending on the channel, and I haven't set a timeout, I exit. If a timeout is set and nothing is available, then I wait for either the timeout or for something to be available on the channel. I'd love to combine this into a single select, but I can't see how I can do that. Any idea?

like image 345
Scott Deerwester Avatar asked May 15 '26 05:05

Scott Deerwester


1 Answers

This is an old question, but since the only answer is poor, I feel like addressing it. The better solution is to use a nil channel, which greatly simplifies the code to not need two separate select statements:

done := false

for !done {
    var timerC <-chan time.Time
    if timeout > 0 {
        timerC = time.After(timeout)
    }
    select {
        case value := <-somechannel:
            // Do something with value
        case <-timerC:
            done = true
        }
    }
}

A case branch a nil channel will do nothing.

like image 88
Alexander Staubo Avatar answered May 18 '26 05:05

Alexander Staubo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!