How to Range Over Channel in Go: Syntax and Examples
In Go, you can use
for range to receive values from a channel until it is closed. The syntax is for val := range ch, where ch is the channel. This loop automatically stops when the channel is closed.Syntax
The syntax to range over a channel uses the for range loop. It receives values from the channel one by one until the channel is closed.
val: variable to hold each received valuech: the channel to receive from- The loop ends automatically when
chis closed
go
for val := range ch { // use val }
Example
This example shows how to send integers to a channel and use for range to receive and print them until the channel is closed.
go
package main import ( "fmt" ) func main() { ch := make(chan int) go func() { for i := 1; i <= 5; i++ { ch <- i } close(ch) // Close channel to end range loop }() for val := range ch { fmt.Println(val) } }
Output
1
2
3
4
5
Common Pitfalls
Common mistakes when ranging over channels include:
- Not closing the channel, which causes the
for rangeloop to block forever. - Trying to send on a closed channel, which causes a panic.
- Using
for val := range chwithout a goroutine sending data, causing deadlock.
go
package main import "fmt" func main() { ch := make(chan int) // Wrong: no goroutine sending data and no close // for val := range ch { // fmt.Println(val) // This will block forever // } // Correct way: go func() { ch <- 1 ch <- 2 close(ch) }() for val := range ch { fmt.Println(val) } }
Output
1
2
Quick Reference
Tips for ranging over channels:
- Always close the channel when no more values will be sent.
- Use a goroutine to send values if the main goroutine is receiving.
- The
for rangeloop stops automatically on channel close.
Key Takeaways
Use
for val := range ch to receive values from a channel until it is closed.Always close the channel to avoid blocking the range loop forever.
Send values on the channel from a separate goroutine to prevent deadlocks.
The range loop automatically stops when the channel is closed.
Avoid sending on a closed channel to prevent runtime panics.