Go通道路線範例


當使用通道作為函式引數時,可以指定通道是否僅用於傳送或接收值。這種特殊性增加了程式的型別安全性。

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

所有的範例程式碼,都放在 F:\worksp\golang 目錄下。安裝Go程式設計環境請參考:/2/23/798.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