Module 3: Select (The Switchboard)
📚 Module 3: Select
Course ID: GO-111
Subject: The Switchboard
What if you are waiting for data from Two different pipes? If you wait for Pipe A, you might miss something arriving in Pipe B. We solve this using the select statement.
🏗️ Step 1: The Multi-Tasking Waiter
🧩 The Analogy: The Switchboard Operator
Imagine an operator at an old-fashioned telephone switchboard.
- Phone A rings? They answer it.
- Phone B rings? They answer it.
- Goal: They answer whichever one rings First.
🏗️ Step 2: In Code
select {
case msg1 := <-channelA:
fmt.Println("Received from A:", msg1)
case msg2 := <-channelB:
fmt.Println("Received from B:", msg2)
case <-time.After(1 * time.Second):
fmt.Println("Timeout! Nobody called.")
}🏗️ Step 3: Timeouts (The “I’m Done Waiting” Rule)
A Senior Go dev always uses select to implement Timeouts.
- If a database takes more than 5 seconds to answer, we don’t want the user to wait forever.
- We add a
time.Aftercase to the select block to stop waiting and send an error.
🥅 Module 3 Review
- select: Letting a Goroutine wait on multiple channel operations.
- Concurrency Control: Handling complex signal flows easily.
- Timeout: Preventing the app from getting stuck forever.
:::tip Slow Learner Note The select statement is like a “Switch” statement (Module 1), but instead of comparing values, it waits for Events on channels. ::: Riverside. Riverside.