go runtime_error ai_generated true

panic: receive from closed channel (returned zero value)

ID: go/channel-receive-from-closed

Also available as: JSON · Markdown · 中文
80%Fix Rate
86%Confidence
0Evidence
2024-04-12First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.0 active
1.22 active

Root Cause

Receiving from a closed channel returns the zero value immediately, which may cause logic errors if not handled.

generic

中文

从已关闭的通道接收会立即返回零值,如果处理不当可能导致逻辑错误。

Workarounds

  1. 95% success
    Use the two-value receive form: v, ok := <-ch; if !ok { /* channel closed */ }
  2. 90% success
    Use a done channel to signal closure and avoid receiving from closed channels.

Dead Ends

Common approaches that don't work:

  1. 80% fail

    The zero value may be indistinguishable from real data, causing incorrect behavior.

  2. 60% fail

    This may skip important data or break the program's flow.

  3. 50% fail

    The boolean is only available in the two-value receive form; if not used, it's missed.