Go通道路線實例

當使用通道作爲函數參數時,可以指定通道是否僅用於發送或接收值。這種特殊性增加了程序的類型安全性。

ping功能只接受用於發送值的通道。嘗試在此頻道上接收將是一個編譯時錯誤。ping函數接受一個通道接收(ping),一個接收發送(ping)。

所有的示例代碼,都放在 F:\worksp\golang 目錄下。安裝Go編程環境請參考: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)
}

執行上面代碼,將得到以下輸出結果 -

F:\worksp\golang>go run channel-directions.go
passed message