Skip to content

Go Channel Range

DodaTech 2 min read

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
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

  1. Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
  2. Using head and tail instead of pattern matching, causing runtime errors on empty lists
  3. 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

**Can I break out of range early?**

Yes, just use break. The goroutine may block if not closed.

What if multiple goroutines send to one channel?

Use a sync.WaitGroup for the sender side, then close after all done.

Does range work on nil channel?

It blocks forever (no iteration).


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