Go Channel Range
In this tutorial, you'll learn about Go Channel: Range Iteration Not Ending. We cover key concepts, practical examples, and best practices.
Channel range loop -- Use range to read from channels until they are closed by the sender.
The Problem
range over a channel continues until the channel is closed. Forgetting to close causes the range loop to hang forever.
Wrong
ch := make(chan int)
go func() {
for i := 0; i < 5; i++ {
ch <- i
}
// Missing close(ch)!
}()
for val := range ch {
fmt.Println(val)
}
// Hangs forever after 5 values!
Output:
0 1 2 3 4 // Then hangs forever
Right
ch := make(chan int)
go func() {
for i := 0; i < 5; i++ {
ch <- i
}
close(ch) // Signal no more values
}()
for val := range ch {
fmt.Println(val)
}
Output:
0
1
2
3
4
// Exits cleanly after close
Prevention
- range loop reads until channel is closed
- Only sender should close
- Always close to prevent range from hanging
- Use break to exit range early without close
- Fan-in patterns need separate close coordination
Common Mistakes with channel range
- Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
- Using
headandtailinstead of pattern matching, causing runtime errors on empty lists - Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
These mistakes appear frequently in real-world GO code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro. DodaTech tutorials help Go developers build production-ready software used by millions.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro