go runtime_error ai_generated true

panic: close of nil channel

ID: go/channel-close-nil-channel

Also available as: JSON · Markdown · 中文
80%Fix Rate
90%Confidence
0Evidence
2024-06-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.0+ active — — —

Root Cause

Attempting to close a channel that has not been initialized (nil).

generic

中文

试图关闭一个未初始化的 channel(nil)。

Workarounds

  1. 98% success
    ch := make(chan int)
    // later
    close(ch)
  2. 90% success
    var once sync.Once
    closeCh := func() {
        if ch != nil {
            once.Do(func() { close(ch) })
        }
    }

Dead Ends

Common approaches that don't work:

  1. 80% fail

    If the channel is nil, closing it is still a panic; you must avoid the close entirely

  2. 70% fail

    Recovering hides the bug and may leave resources in inconsistent state