0
0
Goprogramming~5 mins

Select with multiple channels in Go - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is the purpose of the select statement in Go?
The select statement lets a Go program wait on multiple channel operations. It blocks until one of the channels is ready to send or receive, then executes the corresponding case.
Click to reveal answer
intermediate
How does Go decide which select case to run if multiple channels are ready?
If multiple channels are ready, Go picks one case at random to run. This prevents starvation and ensures fairness.
Click to reveal answer
beginner
What happens if none of the channels in a select statement are ready?
The select statement blocks and waits until one of the channels becomes ready, unless there is a default case, which runs immediately if no channels are ready.
Click to reveal answer
beginner
Write a simple Go select statement that listens on two channels ch1 and ch2 and prints which channel received data.
select { case msg1 := <-ch1: fmt.Println("Received from ch1:", msg1) case msg2 := <-ch2: fmt.Println("Received from ch2:", msg2) }
Click to reveal answer
intermediate
What is the role of the default case in a select statement?
The default case runs immediately if no other channel operations are ready. It prevents blocking and can be used to perform non-blocking checks.
Click to reveal answer
What does the select statement do in Go?
AWaits on multiple channel operations and executes one that is ready
BCreates a new goroutine
CDeclares a new channel
DLocks a mutex
If multiple channels are ready in a select, how does Go choose which case to run?
ARuns the first case declared
BPicks one case at random
CRuns all ready cases simultaneously
DReturns an error
What happens if no channels are ready and there is no default case in a select?
AThe <code>select</code> blocks until a channel is ready
BThe program panics
CThe <code>select</code> skips all cases
DThe <code>select</code> runs the last case
What is the purpose of the default case in a select?
ATo handle errors
BTo close all channels
CTo run code if no channels are ready, avoiding blocking
DTo create new channels
Which of these is a valid use of select with multiple channels?
Aselect { for ch1: ... }
Bselect { ch1 <- 1; ch2 <- 2 }
Cselect { if ch1 == ch2: ... }
Dselect { case <-ch1: ... case <-ch2: ... }
Explain how the select statement works with multiple channels in Go.
Think about how Go handles multiple channel operations at once.
You got /5 concepts.
    Describe a real-life situation where using select with multiple channels would be helpful.
    Imagine you are waiting for messages from different friends on separate phones.
    You got /4 concepts.