go
runtime_error
ai_generated
true
panic: 关闭 nil channel
panic: close of nil channel
ID: go/panic-close-of-nil-channel
80%修复率
88%置信度
0证据数
2024-05-10首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 1.18 | active | — | — | — |
| 1.22 | active | — | — | — |
根因分析
对一个从未用 make() 初始化的 channel 变量调用 close(),其值为 nil 零值。
English
close() is called on a channel variable that was never initialized with make(), so it holds the nil zero value.
解决方案
-
95% 成功率
Initialize the channel at declaration: ch := make(chan int). Never use var ch chan int without assignment if it will be closed.
-
93% 成功率
Use a struct constructor that always makes the channel, e.g. func NewWorker() *Worker { return &Worker{jobs: make(chan Job)} }.
无效尝试
常见但无效的做法:
-
75% 失败
Skipping the close leaves the channel open forever, so receivers block indefinitely; the underlying logic bug remains.
-
85% 失败
Creating a fresh channel at close time means no other goroutine holds a reference to it; the close is meaningless.