go runtime_error ai_generated true

panic: runtime error: send on nil channel

ID: go/nil-channel-send

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.18 active
1.21 active

Root Cause

Attempting to send on a channel that is nil (not initialized with make)

generic

中文

尝试向未使用make初始化的空通道发送数据

Workarounds

  1. 95% success Initialize channel with make before any send operation
    ch := make(chan int, 10)
    ch <- 42
  2. 90% success Use sync.Once to ensure channel initialization is done once
    var once sync.Once
    var ch chan int
    once.Do(func() {
        ch = make(chan int)
    })
    ch <- 42

Dead Ends

Common approaches that don't work:

  1. Using a global variable without initialization 90% fail

    Global channel variables default to nil; forgetting to initialize with make leads to panic

  2. Assuming channel is initialized after function returns 80% fail

    If the channel is assigned inside a goroutine, it may still be nil when another goroutine tries to send