在将通道作为函数参数时,可以指定通道是仅用于发送值还是接收值。这种具体性增加了程序的类型安全性。
package main
import "fmt"
// 这个 ping 函数只接受用于发送值的通道。如果尝试在该通道上接收值,将会导致编译时错误。
func ping(pings chan<- string, msg string) {
pings <- msg
}
// pong 函数接受一个用于接收(ping)的通道和一个用于发送(pong)的通道。
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原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。