0
0
Goprogramming~5 mins

Default case in select in Go - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is the purpose of the default case in a Go select statement?
The default case runs immediately if no other case in the select is ready. It prevents the select from blocking and allows the program to continue.
Click to reveal answer
beginner
Can a select statement in Go block if it has a default case?
No. If a select has a default case, it will never block. It will run the default immediately if no other channel operation is ready.
Click to reveal answer
intermediate
What happens if multiple channel operations in a select are ready at the same time?
Go picks one of the ready cases at random to run. If there is a default case, it only runs if no other case is ready.
Click to reveal answer
beginner
Write a simple Go select statement with a default case that prints "No message received" if no channel is ready.
select { case msg := <-ch: fmt.Println("Received:", msg) default: fmt.Println("No message received") }
Click to reveal answer
intermediate
Why might you use a default case in a select statement in Go?
To avoid blocking when waiting on channels, allowing the program to do other work or check conditions repeatedly without getting stuck.
Click to reveal answer
What does the default case in a Go select statement do?
ABlocks until a channel is ready
BRuns immediately if no other case is ready
CCloses all channels
DTerminates the program
If a select statement has a default case, can it ever block?
ANo, never
BYes, always
COnly if channels are closed
DOnly if the default case is empty
What happens if multiple channel cases in a select are ready at the same time?
AThe program panics
BThe first case is always chosen
COne case is chosen at random
DThe default case runs
Which of these is a reason to use a default case in a select?
ATo close channels automatically
BTo wait indefinitely for a message
CTo restart the program
DTo avoid blocking when no channels are ready
What will this code print if channel ch has no message ready?
select {
case msg := <-ch:
    fmt.Println(msg)
default:
    fmt.Println("No message")
}
AIt prints "No message"
BIt prints the message from ch
CIt blocks forever
DIt causes a runtime error
Explain how the default case works in a Go select statement and why it is useful.
Think about what happens when no channels are ready to send or receive.
You got /3 concepts.
    Write a Go select statement with a default case that handles receiving from a channel and prints a message if no data is available.
    Use <code>select</code> with a receive case and a <code>default</code> that prints.
    You got /3 concepts.