Through the previous article, we know how to declare the channel Channel, and send and read data. However, what this article wants to talk about is 单向Channel
, what exactly is a one-way channel Channel?
The so-called 单向Channel信道
, that is, the declared channel Channel, the Channel channel at this moment can only send or read data.
To declare a one-way channel Channel, you can use chan<-
to declare a channel that can only send data, and the type of its channel variable is chan<-
.
The <-chan
declared channel can only accept data, and the type is <-chan
.
var onlyReadChan chan<- readChanType // 声明一个只能写入数据的信道
var onlyWriteChan <-chan writeChanType // 声明一个只能读取数据的信道
package main
import (
"fmt"
)
//定义一个带有 只能发送数据的信道 的参数 函数
func onlySend(ch chan<- string) {
ch <- "秋码记录"
ch <- "https://qiucode.cn"
}
//定义一个带有 只能接受数据的信道 的参数 函数
func onlyRead(ch <-chan string) {
for {
fmt.Println(<-ch)
}
}
func main() {
var ch = make(chan string)
go onlySend(ch)
go onlyRead(ch)
}