![]() |
VOOZH | about |
In Go, the select statement allows you to wait on multiple channel operations, such as sending or receiving values. Similar to a switch statement, select enables you to proceed with whichever channel case is ready, making it ideal for handling asynchronous tasks efficiently.
Consider a scenario where two tasks complete at different times. We’ll use select to receive data from whichever task finishes first.
Task 1 completed
Note: After 2 seconds,
Task 1 completedwill be printed becausetask1completes beforetask2. Iftask2finished first, thenTask 2 completedwould be printed.
The select statement in Go listens to multiple channel operations and proceeds with the first ready case.
select {
case value := <-channel1:
// Executes if channel1 is ready to send/receive
case channel2 <- value:
// Executes if channel2 is ready to send/receive
default:
// Executes if no other case is ready
}select waits until at least one channel operation is ready.default case executes if no other case is ready, avoiding a block.Table of Content
In this variation, we modify the earlier example by removing the select statement and observe blocking behavior when no channels are ready.
Example
No channels are ready
Explanation: Here, the
defaultcase ensures thatselectdoesn’t block if no channels are ready, printing"No channels are ready".
If both tasks are ready at the same time, select chooses one case randomly. This can happen if tasks have similar sleep times.
Example
Welcome to channel 1
Explanation: In this scenario,
selectrandomly picks one of the two cases if both are ready at the same time, meaning you may see"Task 1 completed"or"Task 2 completed"depending on the selection.
Using default ensures the program does not block if no case is ready. Here’s an example modifying the base structure to include a default case.
Example
No tasks are ready yet
Explanation: Since neither
ch1norch2is ready, thedefaultcase executes, outputting"No tasks are ready yet".
If a select statement is empty (i.e., contains no cases), it blocks indefinitely. This is often used in cases where an infinite wait is necessary, but here’s what it looks like using our channels.
Explanation: Since there are no cases, select will block permanently, causing a deadlock if there are no other goroutines active.