go runtime_error ai_generated true

fatal error: all goroutines are asleep - deadlock! (range over channel)

ID: go/channel-range-without-close

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.19 active

Root Cause

Ranging over a channel that is never closed and has no more values blocks forever.

generic

中文

在从未关闭且没有更多值的通道上进行范围遍历会永久阻塞。

Workarounds

  1. 95% success
    ch := make(chan int)
    go func() { defer close(ch); for i:=0;i<5;i++ { ch<-i } }()
    for v := range ch {
        fmt.Println(v)
    }
  2. 90% success
    for {
        select {
        case v, ok := <-ch:
            if !ok { return }
            fmt.Println(v)
        case <-time.After(time.Second):
            return
        }
    }

Dead Ends

Common approaches that don't work:

  1. 70% fail

    Break only exits if condition met; if no values, still blocks.

  2. 90% fail

    Range doesn't support timeout; need select.

  3. 60% fail

    If the channel is never sent to, still blocks.