The select Statement
Start with The select Statement
In this lesson, explore the select statement through one small Go program, and connect its output to the language rules behind it.
What you’ll learn
- Explain the main purpose of the select statement.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
A select waits for one of several channel operations to proceed. If multiple cases are ready, Go chooses a ready case; do not depend on a particular choice.
A default case makes a select nonblocking, but can also create busy loops if used without care.
Visualize how it works
Follow this diagram before executing the example. Check where a value or decision changes what runs next.
Run a complete Go example
This example is a complete program. Save it as main.go or paste it into the Go Playground.
Go code
package main
import "fmt"
func main() {
left := make(chan string, 1)
right := make(chan string, 1)
left <- "left"
select {
case msg := <-left:
fmt.Println(msg)
case msg := <-right:
fmt.Println(msg)
}
}
Output
leftTrace what the program does
Only left has a value ready, so select reliably chooses it and prints left.
Avoid common mistakes
- If several cases can proceed, their selection is not source-order priority.
- A select with no cases blocks forever.
Try it yourself
Add a default branch and see what it prints when both channels are empty.
Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.
Check your understanding
What you should remember
You have practiced The select Statement in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.
Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.
Reaching the recap and completing the quizzes are separate milestones.