go type_error ai_generated true

panic: send on receive-only channel

ID: go/channel-direction-mismatch

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.18 active
1.19 active

Root Cause

Attempting to send on a channel that is declared as receive-only (<-chan), or receive on a send-only channel (chan<-). This is a compile-time error, but can occur if type assertions are used incorrectly at runtime.

generic

中文

尝试向声明为只接收(<-chan)的通道发送数据,或在只发送(chan<-)通道上接收。这是编译时错误,但如果类型断言使用不当,可能在运行时发生。

Workarounds

  1. 98% success
    func producer(ch chan<- int) {
        ch <- 1
    }
    
    func consumer(ch <-chan int) {
        v := <-ch
        fmt.Println(v)
    }
    
    ch := make(chan int)
    go producer(ch)
    consumer(ch)
  2. 95% success
    ch := make(chan int)
    
    go func(ch chan<- int) {
        ch <- 42
    }(ch)
    
    v := <-ch
    fmt.Println(v)

Dead Ends

Common approaches that don't work:

  1. 100% fail

    Type assertions cannot change channel direction; it's a static property.

  2. 100% fail

    The program will panic or fail to compile.