0
0
Goprogramming~10 mins

Select with multiple channels in Go - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Select with multiple channels
Start
Wait for any channel
Chan1
Handle
Repeat or Exit
The program waits for messages from multiple channels and handles whichever is ready first, including a default case if none are ready.
Execution Sample
Go
package main
import "fmt"
func main() {
 c1 := make(chan string)
 c2 := make(chan string)
 select {
 case msg1 := <-c1:
  fmt.Println("Received", msg1)
 case msg2 := <-c2:
  fmt.Println("Received", msg2)
 default:
  fmt.Println("No message received")
 } 
}
This code waits to receive from two channels and prints the message received or a default message if none are ready.
Execution Table
StepSelect CaseChannel Ready?Action TakenOutput
1case msg1 := <-c1NoSkipped
2case msg2 := <-c2NoSkipped
3defaultN/AExecutedNo message received
4EndN/AProgram ends
💡 No channels were ready, so default case executed and program ended.
Variable Tracker
VariableStartAfter Select
msg1undefinedundefined
msg2undefinedundefined
Key Moments - 2 Insights
Why does the default case run even though channels exist?
Because neither channel had data ready to receive, so select immediately runs the default case as shown in execution_table row 3.
What happens if multiple channels are ready at the same time?
Select picks one at random to execute. This is not shown here but is important to know for concurrency.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, which step shows the default case running?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
Check the 'Action Taken' and 'Output' columns in the execution_table.
At which step does the program decide no channels are ready?
AStep 3
BStep 4
CStep 1
DStep 2
💡 Hint
Look at the 'Channel Ready?' column and when default executes.
If c1 had a message ready, what would change in the execution table?
ADefault case would still run
BStep 1 would execute and print the message
CStep 2 would execute instead
DProgram would deadlock
💡 Hint
Refer to how select picks the first ready channel case to execute.
Concept Snapshot
select {
 case <-chan1:
  // handle chan1
 case <-chan2:
  // handle chan2
 default:
  // handle no ready channel
}

- Waits for multiple channels
- Executes first ready case
- Default runs if none ready
- Useful for concurrent waits
Full Transcript
This example shows how Go's select statement waits for multiple channels. It checks each channel to see if it has data ready. If none are ready, the default case runs immediately. The execution table shows each step: first checking channel 1, then channel 2, then default. Variables msg1 and msg2 remain undefined because no data was received. Key points include that default runs only if no channels are ready, and if multiple channels are ready, select picks one randomly. The quiz tests understanding of which step runs default and what happens if a channel is ready.