# 恐慌：关闭已关闭的通道

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

## 根因

尝试关闭一个已经关闭的通道。

## 版本兼容性

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

## 解决方案

1. **Use sync.Once to ensure close is called only once** (95% 成功率)
   ```
   var closeOnce sync.Once
closeOnce.Do(func() { close(ch) })
   ```
2. **Design with a single producer that closes the channel** (90% 成功率)
   ```
   Only one goroutine should close the channel; use a dedicated closer goroutine.
   ```

## 无效尝试

- **Checking if channel is closed before closing via a flag** — Race condition: two goroutines may both see the flag as false and attempt close. (80% 失败率)
- **Using recover() to catch panic** — recover() catches panics but closing a closed channel is a programming error; better to prevent. (70% 失败率)
