Skip to content

Go Channel Select

DodaTech 1 min read

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
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

  1. Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
  2. Non-exhaustive pattern matches that compile with warnings then crash at runtime
  3. Misunderstanding that String is [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

**Is select fair?**

Yes. Random selection when multiple cases are ready.

Can I select on send?

Yes. case ch <- val: works in select.

What happens if no case is ready and no default?

select blocks until one case is ready.


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