go runtime_error ai_generated true

panic: receive from closed channel (in select)

ID: go/goroutine-select-on-closed-channel

Also available as: JSON · Markdown · 中文
80%Fix Rate
85%Confidence
0Evidence
2025-06-30First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.0 active
1.22 active

Root Cause

Selecting on a closed channel immediately receives zero values, which may cause unexpected behavior if not handled.

generic

中文

在已关闭的通道上select会立即接收零值,如果不处理可能导致意外行为。

Workarounds

  1. 95% success Use two-value receive to check if channel is closed
    select {
    case val, ok := <-ch:
        if !ok {
            // channel closed
        }
        // process val
    }
  2. 85% success Set channel to nil after close to disable it
    close(ch)
    ch = nil
    select {
    case <-ch: // blocked because nil
    }

Dead Ends

Common approaches that don't work:

  1. Ignoring closed channel in select 70% fail

    Closed channel always returns zero value immediately; select may not behave as expected.

  2. Using recover() to catch zero value 90% fail

    Receive from closed channel doesn't panic; it returns zero value with ok=false.