Concept Flow - Default case in select
Start select
Check channels ready?
No→Default case runs
Yes
Run ready channel case
End select
The select statement checks if any channel is ready. If none are ready, it runs the default case immediately.
select {
case msg := <-ch1:
fmt.Println("Received", msg)
default:
fmt.Println("No message received")
}| Step | Channel ch1 ready? | Action | Output |
|---|---|---|---|
| 1 | No | Run default case | No message received |
| 2 | Yes | Receive from ch1 | Received <message> |
| Variable | Start | After Step 1 | After Step 2 |
|---|---|---|---|
| msg | undefined | undefined | <message from ch1> |
select {
case <-ch1:
// runs if ch1 ready
default:
// runs if no channels ready immediately
}
Default case prevents blocking by running instantly if no channel is ready.What does the default case do in a Go select statement?
selectselect statement waits on multiple channel operations.defaultdefault case runs immediately if no channels are ready, preventing blocking.default runs when no channels ready = A [OK]Which of the following is the correct syntax for using a default case in a Go select?
select {
case msg := <-ch1:
fmt.Println(msg)
// What goes here?
}select syntaxdefault keyword is used for the fallback case in select.default is valid; else, fallback, and otherwise are invalid in Go select.default keyword in select = C [OK]What will be the output of this Go program?
package main
import (
"fmt"
"time"
)
func main() {
ch := make(chan string)
select {
case msg := <-ch:
fmt.Println(msg)
default:
fmt.Println("No message received")
}
}ch is created but no data is sent, so it's empty and no receive is ready.ch, the default case runs immediately, printing "No message received".Identify the error in this Go code snippet using select with a default case:
select {
case msg := <-ch:
fmt.Println(msg)
default
fmt.Println("No message")
}default syntaxdefault case requires a colon (:) after the keyword.default without a colon, causing a syntax error.Consider this Go program snippet:
ch1 := make(chan int)
ch2 := make(chan int)
go func() {
time.Sleep(100 * time.Millisecond)
ch1 <- 1
}()
go func() {
time.Sleep(200 * time.Millisecond)
ch2 <- 2
}()
select {
case val := <-ch1:
fmt.Println("Received from ch1:", val)
case val := <-ch2:
fmt.Println("Received from ch2:", val)
default:
fmt.Println("No channels ready")
}What is the most likely output when this select runs?
select runs immediately.select runs, neither channel has data ready, so no case is ready.default case runs, printing "No channels ready".Pass the test and this pattern moves unknown