Go Channel Select
In this tutorial, you'll learn about Go Channel: Select Statement. We cover key concepts, practical examples, and best practices.
Channel select -- Use select statements to wait on multiple channel operations simultaneously.
The Problem
select picks one random ready case when multiple are ready. This is intentional to prevent starvation. Use select for timeouts, cancellation, and non-blocking sends/receives.
Wrong
select {
case val := <-ch1:
fmt.Println("Got from ch1:", val)
case val := <-ch2:
fmt.Println("Got from ch2:", val)
default:
fmt.Println("No channels ready")
}
Output:
// If both channels ready, random one chosen
Right
select {
case val := <-ch1:
fmt.Println(ch1, val)
case val := <-ch2:
fmt.Println(ch2, val)
case <-time.After(5 * time.Second):
fmt.Println("Timeout!")
case <-ctx.Done():
fmt.Println("Cancelled:", ctx.Err())
default:
fmt.Println("Non-blocking check")
}
Output:
// Timeout after 5 seconds if no channel ready
Prevention
- select with multiple ready cases picks randomly
- Use default for non-blocking operations
- Use time.After for timeout patterns
- Use ctx.Done() for cancellation
- Empty select{} blocks forever
Common Mistakes with channel select
- Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
- Misunderstanding that
Stringis[Char]with poor performance for large text operations
These mistakes appear frequently in real-world GO code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro. DodaTech tutorials help Go developers build production-ready software used by millions.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro