Go Select Statement

What is Select?

The select statement lets you wait on multiple channel operations at the same time.

It chooses one of the ready channels and executes its case.

Loading...
Output:

Why Use Select?

Select is useful when working with multiple goroutines and channels.

  • Handle multiple inputs
  • Prevent blocking on one channel
  • Improve concurrency control

Basic Example

This example listens to two channels and prints whichever sends data first.

Loading...
Output:

Multiple Select Executions

You can run select inside a loop to continuously listen to channels.

This is useful for long-running concurrent programs.

Loading...
Output:

Default Case (Non-Blocking)

The default case runs if no channel is ready.

This makes the select statement non-blocking.

Loading...
Output:

Timeout with Select

You can use select with time.After to create timeouts.

This prevents waiting forever for a channel.

Loading...
Output:

Real-World Example

Select is commonly used in servers, workers, and event-driven systems.

Loading...
Output:

Why Select is Important

Select is essential for advanced concurrency in Go.

  • Handles multiple channels efficiently
  • Prevents deadlocks
  • Used in real-world systems

Common Mistakes

Be careful with these:

  • Forgetting default when non-blocking is needed
  • Deadlocks when no channels are ready
  • Assuming execution order

Practice

Create two goroutines that send messages to different channels. Use select to receive both.

Loading...
Output:

Need Help?