Go基础 专题
专题目录
您的位置:go > Go基础 专题 > Go通道路线实例
Go通道路线实例
作者:--    发布时间:2019-11-20

当使用通道作为函数参数时,可以指定通道是否仅用于发送或接收值。这种特殊性增加了程序的类型安全性。

ping功能只接受用于发送值的通道。尝试在此频道上接收将是一个编译时错误。ping函数接受一个通道接收(ping),一个接收发送(ping)。

所有的示例代码,都放在 f:\worksp\golang 目录下。安装go编程环境请参考:http://www.h3.com/go/go_environment.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

网站声明:
本站部分内容来自网络,如您发现本站内容
侵害到您的利益,请联系本站管理员处理。
联系站长
373515719@qq.com
关于本站:
编程参考手册