go type_error ai_generated true

恐慌:向只接收通道发送数据

panic: send on receive-only channel

ID: go/channel-direction-mismatch

其他格式: JSON · Markdown 中文 · English
80%修复率
80%置信度
0证据数
2024-12-01首次发现

版本兼容性

版本状态引入弃用备注
1.18 active
1.19 active

根因分析

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

English

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

解决方案

  1. 98% 成功率
    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% 成功率
    ch := make(chan int)
    
    go func(ch chan<- int) {
        ch <- 42
    }(ch)
    
    v := <-ch
    fmt.Println(v)

无效尝试

常见但无效的做法:

  1. 100% 失败

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

  2. 100% 失败

    The program will panic or fail to compile.