Go Select
Go's select statement lets you wait on multiple channel operations. Combining select with goroutines and channels is a powerful feature of Go.
1. Basic Example
select blocks until one of its cases can run, then it executes that case. It's like a switch statement but for channels.
2. Timeouts
You can use select with time.After to prevent a program from waiting forever on a channel.
3. Non-Blocking Channel Operations
If a default case is present, the select statement becomes non-blocking. It will try to send/receive, and if it can't, it immediately executes the default code.
Important Notes
- Fairness: If multiple channels are ready at the same time, Go picks one at random.
- Empty Select: An empty select
select {}will block forever. - Sending:
selectalso works for sending:case c1 <- "data":. This will run only ifc1is ready to accept data.