Skip to content

Go Channel Close

DodaTech 1 min read

In this tutorial, you'll learn about Go Channel: Closing Channels. We cover key concepts, practical examples, and best practices.

Channel close pattern -- Follow the rule: only the sender closes the channel, never the receiver, and never close a closed channel.

The Problem

Closing a channel signals receivers that no more values are coming. Sending on a closed channel panics. Closing a channel twice panics. Always let the sender close.

Wrong

ch := make(chan int)
close(ch)
ch <- 42 // panic: send on closed channel!

Output:

// Runtime panic. Program crashes.
ch := make(chan int)
go func() {
    for i := 0; i < 5; i++ {
        ch <- i
    }
    close(ch) // Sender closes
}()
for val := range ch {
    fmt.Println(val) // Receiver reads until close
}

Output:

0
1
2
3
4

Prevention

  • Only the sender closes the channel
  • Never close a channel twice
  • Use range to read until channel close
  • Check ok on receive: val, ok := <-ch (ok=false when closed)
  • Closing a nil channel panics

Common Mistakes with channel close

  1. Forgetting deriving (Show, Eq) on custom data types needed for debugging
  2. Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
  3. Using head and tail instead of pattern matching, causing runtime errors on empty lists

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

**What happens if receiver closes?**

Panic: close of channel that receiver shouldn't close.

How to detect closed channel without range?

val, ok := <-ch. ok is false when closed.

Should I close a channel that others may still send to?

Never. Only the sender closes.


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