go
runtime_error
ai_generated
true
恐慌:运行时错误:向空通道发送数据
panic: runtime error: send on nil channel
ID: go/nil-channel-send
80%修复率
85%置信度
0证据数
2024-04-01首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 1.18 | active | — | — | — |
| 1.21 | active | — | — | — |
根因分析
尝试向未使用make初始化的空通道发送数据
English
Attempting to send on a channel that is nil (not initialized with make)
解决方案
-
95% 成功率 Initialize channel with make before any send operation
ch := make(chan int, 10) ch <- 42
-
90% 成功率 Use sync.Once to ensure channel initialization is done once
var once sync.Once var ch chan int once.Do(func() { ch = make(chan int) }) ch <- 42
无效尝试
常见但无效的做法:
-
Using a global variable without initialization
90% 失败
Global channel variables default to nil; forgetting to initialize with make leads to panic
-
Assuming channel is initialized after function returns
80% 失败
If the channel is assigned inside a goroutine, it may still be nil when another goroutine tries to send