The select statement in Go allows concurrent waiting on multiple channel operations, executing the first one that is ready.
Use the select statement to wait on multiple channel operations simultaneously, executing the first one that becomes ready.
select {
case msg := <-ch1:
fmt.Println("Received from ch1:", msg)
case ch2 <- "hello":
fmt.Println("Sent to ch2")
default:
fmt.Println("No channel ready")
}
The default case executes immediately if no other case is ready, making the select non-blocking.
The select statement lets your program wait for multiple events at once, like receiving data from different sources or sending data to different destinations. It picks the first event that happens and runs that code block, ignoring the rest. Think of it like a waiter at a busy restaurant who only takes the order from the first customer who raises their hand.