# 恐慌：运行时错误：关闭空通道

- **ID:** `go/panic-runtime-error-close-of-nil-channel`
- **领域:** go
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 95%

## 根因

尝试使用 close(ch) 关闭一个尚未初始化（空值）的通道变量。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| go1.20 | active | — | — |
| go1.21 | active | — | — |
| go1.22 | active | — | — |

## 解决方案

1. ```
   使用 make() 初始化通道后再使用：ch := make(chan T); defer close(ch)
   ```
2. ```
   在 close 前进行空值检查：if ch != nil { close(ch) } else { /* 处理空值情况 */ }
   ```
3. ```
   使用 sync.Once 确保 close 只调用一次且在初始化之后：var closeOnce sync.Once; closeOnce.Do(func() { close(ch) })
   ```

## 无效尝试

- **Wrap close(ch) in a recover() block to catch the panic** — Recovering doesn't fix the root cause and may mask a logic error (70% 失败率)
- **Use select with default to check if channel is nil before closing** — select doesn't detect nil channels at compile time; it's a runtime check that still panics if nil (80% 失败率)
- **Set ch = make(chan T) before every close call** — Overwrites the existing channel and may cause goroutine leaks or lost messages (60% 失败率)
