Don't Select The Default
From other languages, or even from Go's switch
statement, you might be used to adding a default:
case as a fallback.
Be wary of doing that in a select
statement.
for {
select {
case <- ch1:
do1()
case ch2 <- val:
do2()
default:
// do nothing
}
}
The select
semantics make each case block until one of the channels delivers a value or is ready to receive a value. If a default
clause is present, it will be invoked if all other cases are blocked.
However, if the default
case does nothing, you've just created a tightly spinning for
loop!
While this empty default
case does not affect the logic of the select
statement, it will keep your CPU busy. So if in doubt, leave it out.
for {
select {
case <- ch1:
do1()
case ch2 <- val:
do2()
}
}