go runtime_error ai_generated true

panic: select on closed channel

ID: go/select-random-choice

Also available as: JSON · Markdown · 中文
80%Fix Rate
84%Confidence
0Evidence
2024-03-30First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.20 active

Root Cause

A select statement includes a case that sends to a closed channel, causing a panic when selected.

generic

中文

select 语句中包含向已关闭通道发送的 case,当该 case 被选中时引发 panic。

Workarounds

  1. 90% success
    Before sending, check if channel is closed using a separate mechanism: 
    
    select {
    case <-done:
        return
    case ch <- v:
    }
    // Ensure done is closed before ch is closed.
  2. 85% success
    Use a separate struct with a mutex to manage channel state, or use a single producer that closes the channel.

Dead Ends

Common approaches that don't work:

  1. 50% fail

    If the channel is closed dynamically, it can't be removed at compile time.

  2. 80% fail

    Default case doesn't prevent panic when sending on a closed channel that is selected.