当使用通道作为函数参数时,可以指定通道是否仅用于发送或接收值。这种特殊性增加了程序的类型安全性。
此ping
功能只接受用于发送值的通道。尝试在此频道上接收将是一个编译时错误。ping
函数接受一个通道接收(ping
),一个接收发送(ping
)。
所有的示例代码,都放在
F:\worksp\golang
目录下。安装Go编程环境请参考:/tutorial/detail-5562.html
channel-synchronization.go
的完整代码如下所示 -
package main import "fmt" // This `ping` function only accepts a channel for sending // values. It would be a compile-time error to try to // receive on this channel. func ping(pings chan<- string, msg string) { pings <- msg } // The `pong` function accepts one channel for receives // (`pings`) and a second for sends (`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) }
执行上面代码,将得到以下输出结果 -
F:\worksp\golang>go run channel-directions.go passed message