當(dāng)使用通道作為函數(shù)參數(shù)時(shí),可以指定通道是否僅用于發(fā)送或接收值。這種特殊性增加了程序的類型安全性。
此ping功能只接受用于發(fā)送值的通道。嘗試在此頻道上接收將是一個(gè)編譯時(shí)錯(cuò)誤。ping函數(shù)接受一個(gè)通道接收(ping),一個(gè)接收發(fā)送(ping)。
所有的示例代碼,都放在
F:\worksp\golang目錄下。安裝Go編程環(huán)境請(qǐng)參考:http://www.yiibai.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)
}
執(zhí)行上面代碼,將得到以下輸出結(jié)果 -
F:\worksp\golang>go run channel-directions.go
passed message