go data_error ai_generated true

错误:收到意外的零值(channel 已关闭,忽略了 ok=false)

error: unexpected zero value received (channel closed, ok=false ignored)

ID: go/receive-from-closed-channel-zero-value

其他格式: JSON · Markdown 中文 · English
80%修复率
88%置信度
0证据数
2024-04-08首次发现

版本兼容性

版本状态引入弃用备注
1.18 active — — —
1.21 active — — —

根因分析

从已关闭的 channel 读取会永远立即返回零值。忽略 'ok' 布尔值的代码把零值当作真实数据,造成静默的数据损坏。

English

Reading from a closed channel returns the zero value immediately forever. Code that ignores the 'ok' bool treats zero values as real data, causing silent corruption.

generic

解决方案

  1. 95% 成功率
    Use the comma-ok idiom: 'v, ok := <-ch; if !ok { return }' and break the loop on close
  2. 93% 成功率
    Use 'for v := range ch { ... }' which terminates automatically when the channel closes

无效尝试

常见但无效的做法:

  1. 80% 失败

    Closed channel always returns immediately; sleep just delays the wrong value

  2. 85% 失败

    len is a snapshot and racy; does not distinguish closed from empty