Range and Select

Go provides two powerful control structures for working with channels: range and select.

Ranging over Channels

You can use for range to continuously receive values from a channel until it is closed.

for item := range ch {
    fmt.Println(item)
}
// Loop exits automatically once close(ch) is called and channel is empty

The select Statement

select allows a goroutine to wait on multiple channel operations. It blocks until one of its cases can run, then executes that case.

select {
case msg1 := <-ch1:
    fmt.Println("Received from ch1:", msg1)
case ch2 <- 42:
    fmt.Println("Sent to ch2")
}
  • Blocking: If no cases are ready, select blocks until one is.
  • Randomness: If multiple cases are ready at the same time, Go chooses one randomly.
  • Exit Condition: You can use the “comma ok” idiom inside a case to detect when a channel closes and return from your loop.