Go 只读/只写channel

Go中channel可以是只读、只写、同时可读写的。

//定义只读的channel

read_only := make (<-chan int)

 

//定义只写的channel

write_only := make (chan<- int)

 

//可同时读写

read_write := make (chan int)

 

定义只读和只写的channel意义不大,一般用于在参数传递中,见代码:

package main

import (
    "fmt"
    "time"
)

func main() {
    c := make(chan int)
    go send(c)
    go recv(c)
    time.Sleep(3 * time.Second)
}
//只能向chan里写数据
func send(c chan<- int) {
    for i := 0; i < 10; i++ {
        c <- i
    }
}
//只能取channel中的数据
func recv(c <-chan int) {
    for i := range c {
        fmt.Println(i)
    }
}

 

如果将上面send方法和recv方法中的参数对调:

func send(c <-chanint) {

func recv(c chan<- int) {

编译就会报错:

./channel.go:18: invalid operation: c <- i (send to receive-only type <-chan int)

./channel.go:24: invalid operation: range c (receive from send-only type chan<- int)

转载于:https://www.cnblogs.com/baiyuxiong/p/4545028.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值