026_go语言中的通道方向

代码演示

package main

import "fmt"

func ping(pings chan<- string, msg string) {
	pings <- msg
}
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)
}

 

代码运行结果

passed message

  

代码解读

  • 当使用通道作为参数时,可以指定这个通道是不是只用来发送还是接收一个值,这个特性是为了提升程序的安全性
  • ping函数定义了一个只接收值的的通道
  • pong函数定义了两个通道,第一个用来发送值,第二个用来接收值
  • 整个程序的逻辑是,定义了两个通道,一个是pings,一个是pongs,将通道pings当做参数传给函数ping,pings接收了"passed message"的值
  • 将pings和pongs传给函数pong,那么从通道pings中将值取出来给msg,再由msg传给通道pongs,最终再将pongs中的值取出来打印
posted @ 2018-04-10 22:14  Joestar  阅读(372)  评论(0编辑  收藏  举报