Github仓库Go by Example 中文对应的源代码地址为:channel-directions.go mmcgrana/gobyexample英文原版的代码地址为:channel-directions.go
// 当使用通道作为函数的参数时,你可以指定这个通道是否为只读或只写。
// 该特性可以提升程序的类型安全。
package main
import "fmt"
// `ping` 函数定义了一个只能发送数据的(只写)通道。
// 尝试从这个通道接收数据会是一个编译时错误。
func ping(pings chan<- string, msg string) {
pings <- msg
}
// `pong` 函数接收两个通道,`pings` 仅用于接收数据(只读),`pongs` 仅用于发送数据(只写)。
func pong(pings <-chan string, pongs chan<- string) {
msg := <-pings
pongs <- msg
}
func main() {
pings := make(chan string, 1)
pongs := make(chan string, 1)
ping(pings, "passed message")
pong(pings, pongs)
fmt.Println(<-pongs)
}
运行结果如下:
$ go run channel-directions.go
passed message
下一个例子: 通道选择器.
@mmcgrana 编写 | everyx 翻译 | 项目地址 | license
上面讲解的关于通道方向的不太好记忆,还好在golang官网文档https://golang.org/ref/spec#Channel_types中对于通道的方向有了详细的描述,如下所示:
对于通道方向,有一种简便的记忆方法就是: 就是通道chan标识符在左边,就是发送;通道标识符chan在右边,就是接收。