The default case in a select statement lets your program do something when no other channel is ready. It helps avoid waiting forever.
0
0
Default case in select in Go
Introduction
When you want to check multiple channels but continue if none are ready.
To avoid blocking your program if no data is available on channels.
When you want to perform a fallback action if no communication happens.
To keep your program responsive by not waiting on channels.
When you want to do something else while waiting for channel operations.
Syntax
Go
select {
case <-chan1:
// do something when chan1 is ready
case chan2 <- value:
// send value when chan2 is ready
default:
// do this if no channels are ready
}The default case runs immediately if no other case can proceed.
Without default, select waits (blocks) until a channel is ready.
Examples
This tries to receive from
ch1. If no message is ready, it prints a fallback message.Go
select {
case msg := <-ch1:
fmt.Println("Received", msg)
default:
fmt.Println("No message ready")
}This tries to send 10 to
ch2. If ch2 is not ready to receive, it prints a fallback message.Go
select {
case ch2 <- 10:
fmt.Println("Sent 10 to ch2")
default:
fmt.Println("Could not send to ch2")
}Sample Program
This program tries to receive a message from ch. If no message is ready, it prints a message and waits a bit. After 1 second, the goroutine sends "hello" to ch, so the next select receives it.
Go
package main import ( "fmt" "time" ) func main() { ch := make(chan string) go func() { time.Sleep(1 * time.Second) ch <- "hello" }() for i := 0; i < 3; i++ { select { case msg := <-ch: fmt.Println("Received message:", msg) default: fmt.Println("No message yet, doing other work") time.Sleep(500 * time.Millisecond) } } }
OutputSuccess
Important Notes
Use default to keep your program from freezing when channels are empty.
Without default, select waits until one channel is ready.
Be careful: too many default cases can cause busy loops that waste CPU.
Summary
The default case runs if no channels are ready in a select.
It helps avoid blocking and keeps your program responsive.
Use it for fallback actions or to do other work while waiting.