# panic: close of closed channel (in for range)

- **ID:** `go/goroutine-for-range-channel-close`
- **Domain:** go
- **Category:** runtime_error
- **Verification:** ai_generated
- **Fix Rate:** 80%

## Root Cause

Closing a channel that is being ranged over by another goroutine, causing a panic when the range attempts to read from the closed channel.

## Version Compatibility

| Version | Status | Introduced | Deprecated |
|---------|--------|------------|------------|
| 1.20 | active | — | — |
| 1.21 | active | — | — |

## Workarounds

1. **Use a separate goroutine to close the channel after all sends are done.** (100% success)
   ```
   ch := make(chan int)
go func() {
    for i := 0; i < 10; i++ {
        ch <- i
    }
    close(ch)
}()
for v := range ch {
    fmt.Println(v)
}
   ```
2. **Use a sync.WaitGroup to coordinate closure.** (95% success)
   ```
   var wg sync.WaitGroup
wg.Add(1)
go func() {
    defer wg.Done()
    for i := 0; i < 10; i++ {
        ch <- i
    }
}()
go func() {
    wg.Wait()
    close(ch)
}()
for v := range ch {
    fmt.Println(v)
}
   ```

## Dead Ends

- **Closing the channel inside the range loop.** — Range loop continues until channel is closed, but closing inside causes panic on next iteration. (80% fail)
- **Using a defer close in the sender goroutine that ranges.** — If the sender is also the range receiver, closing inside the loop is problematic. (70% fail)
