Iteration Strategies
Range-Based Iteration
The most common and safe method for iterating over channels is using the range
keyword:
func processChannel(ch <-chan int) {
for value := range ch {
fmt.Println(value)
}
}
Channel Iteration Patterns
1. Basic Range Iteration
func main() {
ch := make(chan int, 5)
// Sending values
for i := 0; i < 5; i++ {
ch <- i
}
close(ch)
// Iterating safely
for value := range ch {
fmt.Println(value)
}
}
2. Select-Based Iteration
func selectIteration(ch <-chan int, done chan bool) {
for {
select {
case value, ok := <-ch:
if !ok {
// Channel is closed
return
}
fmt.Println(value)
case <-time.After(2 * time.Second):
fmt.Println("Timeout")
return
}
}
}
Iteration Strategies Comparison
Strategy |
Pros |
Cons |
Range Iteration |
Simple, Clean |
Blocks until channel closes |
Select Iteration |
More control, Non-blocking |
More complex |
Manual Checking |
Maximum flexibility |
Most verbose |
Channel Iteration Flow
graph TD
A[Start Channel Iteration] --> B{Channel Open?}
B -->|Yes| C[Receive Value]
C --> D[Process Value]
D --> B
B -->|No| E[End Iteration]
Advanced Iteration Techniques
Graceful Shutdown
func gracefulIteration(ch <-chan int, done chan<- bool) {
defer func() { done <- true }()
for value := range ch {
if shouldStop(value) {
return
}
processValue(value)
}
}
Key Considerations
- Always close channels when done sending
- Use buffered channels for performance optimization
- Implement timeout mechanisms for long-running iterations
At LabEx, we emphasize the importance of understanding channel iteration strategies for efficient concurrent programming in Go.