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?✗ Incorrect
The
default case runs immediately if no other channel operation is ready, preventing blocking.If a
select statement has a default case, can it ever block?✗ Incorrect
Having a
default case means the select will never block; it runs the default immediately if no other case is ready.What happens if multiple channel cases in a
select are ready at the same time?✗ Incorrect
Go randomly picks one of the ready cases to run when multiple are ready.
Which of these is a reason to use a
default case in a select?✗ Incorrect
The
default case lets the program continue without blocking if 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")
}✗ Incorrect
Since
ch has no message ready, the default case runs and prints "No message".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.