在GO中,可以指定通道可以发送的方向.我正在try 创建一个有关它的示例,请看下面的代码:

package main

import (
    "fmt"
    "time"
)

func main() {

    ic_send_only := make(<-chan int) //a channel that can only send data - arrow going out is sending
    ic_recv_only := make(chan<- int) //a channel that can only receive a data - arrow going in is receiving

    go func() {
        ic_recv_only <- 4555
    }()

    go func() {

        ic_send_only <- ic_recv_only

    }()

    fmt.Println(ic_recv_only)
    time.Sleep(10000)

}

我得到了编译器错误

# command-line-arguments
.\send_receive.go:19: invalid operation: ic_send_only <- ic_recv_only (send to receive-only type <-chan int)
[Finished in 0.2s with exit code 2]

我怎样才能正确地使用频道方向?

还是有人有比我更好的样本?

推荐答案

三个问题:

  • 您颠倒了发送和接收操作(这就是您看到的错误)
  • 创建只接收或只发送频道毫无意义,因为您无法使用它们
  • 您正在使用的表示法试图发送通道本身,而不是结果.您需要接收and个发送,这需要两个箭头.

    ic_recv_only <- <-ic_send_only

您可能会感到困惑,因为您颠倒了术语.<-ch是"接收操作",ch <-是发送操作.请注意,在您的示例中,所有内容都会死锁,因为您无法完成相应的发送和接收来通过任一通道传递信息.

下面是一个完整的示例:

// This receives an int from a channel. The channel is receive-only
func consumer(ch <-chan int) int {
    return <-ch
}

// This sends an int over a channel. The channel is send-only
func producer(i int, ch chan<- int) {
    ch <- i
}

func main() {
    ch := make(chan int)
    go producer(42, ch)
    result := consumer(ch)
    fmt.Println("received", result)
}

Go相关问答推荐

将Go程序导出到WASM—构建约束排除所有Go文件

Gorm foreign 密钥

如何将泛型函数作为参数传递给golang中的另一个函数?

如何在围棋中从多部分.Part中获取多部分.文件而不保存到磁盘?

如何解析Go-Gin多部分请求中的 struct 切片

Redis:尽管数据存在,但 rdb.Pipelined 中出现redis:nil错误

从带有嵌套括号的字符串中提取值

在 Windows 11 上运行 go mod tidy 时的 gitlab 权限问题

为什么 net/http 不遵守超过 30 秒的超时持续时间?

闭包所处的环境范围是什么?

是否可以从 golang 中的参数推断类型?

Go:如何在将 float64 转换为 float32 时判断精度损失

如何将元素从一个切片移动到另一个切片

将 big.Int 转换为 [2]int64,反之亦然和二进制补码

在 Go GRPC 服务器流式拦截器上修改元数据

Golang泛型在用作 map 元素时不起作用

转到文本/模板模板:如何根据模板本身的值数组判断值?

Go:用于 XML 解码的嵌套 struct 中的提升字段

行之间的模板交替设计

Gin中测试模式有什么用