# panic: 重复关闭 channel

- **ID:** `go/close-of-closed-channel`
- **领域:** go
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

两个 goroutine 都调用了 close(ch)，或函数被重试导致 defer close 执行了两次。Go 在第二次 close 时 panic。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 1.0+ | active | — | — |

## 解决方案

1. **** (97% 成功率)
   ```
   var closeOnce sync.Once
closeOnce.Do(func() { close(ch) })
   ```
2. **** (95% 成功率)
   ```
   // Only the producer closes
func produce(ch chan<- int, n int) {
    defer close(ch)
    for i := 0; i < n; i++ { ch <- i }
}
   ```

## 无效尝试

- **** — The flag itself is racy without a mutex; two goroutines can both read false and both call close. (80% 失败率)
- **** — If the main goroutine is not the sole owner or the function can run concurrently, this does not guarantee single close. (60% 失败率)
