Why This Happens
Closing a channel signals that no more values will be sent. If you send on a closed channel, Go panics. This usually happens when multiple goroutines send to the same channel and one closes it while others are still sending, or when you close a channel too early.
The Problem
func main() {
ch := make(chan int)
close(ch)
ch <- 42 // panic: send on closed channel
}The Fix
func main() {
ch := make(chan int)
go func() {
ch <- 42
close(ch) // close after done sending
}()
for v := range ch {
fmt.Println(v)
}
}Step-by-Step Fix
- 1
Identify who closes the channel
Find the close(ch) call and determine which goroutine calls it.
- 2
Ensure single closer
Only one goroutine should close the channel, typically the sender.
- 3
Coordinate with sync
Use sync.WaitGroup or sync.Once to ensure the channel is closed only after all senders are done.
Bugsly catches this automatically
Bugsly's AI analyzes this error pattern in real-time, explains what went wrong in plain English, and suggests the exact fix — before your users even report it.
Try Bugsly free