Golang 之 协程 goroutine(四)

通道方向 : 当使用通道作为函数的参数时,可以指定这个通道是不是只用来发送或者接收值。这个特性提升了程序的类型安全性。

func ping(pings chan<- string, msg string) {
    pings <- msg

    // 若尝试运行如下语句,发送通道数据,将会报错
    // invalid operation: <-pings (receive from send-only type chan<- string)

    // fmt.Println( <- pings) 
}

当在局部环境内,通道作为参数指明了方向,那么就应该按方向要求,操作通道

package main

import "fmt"

// `ping` 函数定义了一个只允许发送数据的通道。尝试使用这个通
// 道来接收数据将会得到一个编译时错误。
func ping(pings chan<- string, msg string) {
    pings <- msg
}

func pong(pongs <-chan string) {
    fmt.Println(<- pongs)
}

func main() {
    pings := make(chan string, 1)

    ping(pings, "passed message")
    pong(pings)
}

你可能感兴趣的:(golang,Golang王者之路)