select default
A default case in select runs when none of the channel operations can proceed right now. That makes the select non-blocking: try the channels, otherwise continue.
Detailed Explanation
Without default, select waits. With default, it becomes a poll. select { case ch <- v: ... default: ... } sends if there is a receiver or a buffer slot, and otherwise runs default immediately. The same for receive.
Non-blocking send/receive. This is how you try to publish a metric without stalling the request, or try to read a cancellation signal without parking. If default is the common path, you are polling. In a tight loop that is a busy-wait and will burn a CPU core. Pair polling with time.Sleep, or better, block in a select without default until something is ready.
Priority idiom.
select {
case <-urgent:
handleUrgent()
default:
}
select {
case <-urgent:
handleUrgent()
case <-normal:
handleNormal()
}
The first select drains urgent if it is already ready. The second waits for either. That is priority, not fairness.
default with empty other cases is just default. A select { default: } is a no-op.
What it costs. A select with default does not park. Used once, it is cheap. Used in for { select { default: } } it is a spin loop. If you wanted to wait, omit default. If you wanted to wait with a timeout, use time.After or ctx.Done(), not a default plus a sleep inside a hot loop without a wait.
Code Examples
package main
import "fmt"
func trySend(ch chan<- int, v int) bool {
select {
case ch <- v:
return true
default:
return false
}
}
func main() {
ch := make(chan int, 1)
fmt.Println(trySend(ch, 1)) // true
fmt.Println(trySend(ch, 2)) // false, buffer full
}func tryRecv(ch <-chan int) (int, bool) {
select {
case v, ok := <-ch:
return v, ok
default:
return 0, false
}
}func spinBad(ch <-chan int) {
for {
select {
case <-ch:
return
default:
// busy-wait: burns CPU
}
}
}Common Gotchas
`default` in a tight loop is a busy-wait
you will see 100% CPU. Block, or sleep, or use a condition.
A failed try-send drops the value unless you keep it
`default` means "not sent," not "sent later."
`len(ch)` is not a substitute
it races. `select`/`default` is the atomic try.
`default` is never chosen when another case is ready
including a buffered send that fits.