go
runtime_error
ai_generated
true
恐慌:运行时错误:关闭空通道
panic: runtime error: close of nil channel
ID: go/panic-runtime-error-close-of-nil-channel
95%修复率
89%置信度
1证据数
2023-01-20首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| go1.20 | active | — | — | — |
| go1.21 | active | — | — | — |
| go1.22 | active | — | — | — |
根因分析
尝试使用 close(ch) 关闭一个尚未初始化(空值)的通道变量。
English
Attempting to close a channel variable that has not been initialized (nil) using close(ch).
官方文档
https://go.dev/ref/spec#Close解决方案
-
使用 make() 初始化通道后再使用:ch := make(chan T); defer close(ch)
-
在 close 前进行空值检查:if ch != nil { close(ch) } else { /* 处理空值情况 */ } -
使用 sync.Once 确保 close 只调用一次且在初始化之后:var closeOnce sync.Once; closeOnce.Do(func() { close(ch) })
无效尝试
常见但无效的做法:
-
Wrap close(ch) in a recover() block to catch the panic
70% 失败
Recovering doesn't fix the root cause and may mask a logic error
-
Use select with default to check if channel is nil before closing
80% 失败
select doesn't detect nil channels at compile time; it's a runtime check that still panics if nil
-
Set ch = make(chan T) before every close call
60% 失败
Overwrites the existing channel and may cause goroutine leaks or lost messages