循序漸進學 Go:頻道方向

當使用頻道為函數參數時,可以指定頻道是要只用於傳送值還是只接收值。此具體性提升了程式的類型安全性。

package main
import "fmt"

ping 函數只接受頻道來傳送值。會是編譯時期錯誤,若嘗試在此頻道中接收。

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

pong 函數接受一個頻道用於接收(pings)以及第二個頻道用於傳送(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)
}
$ go run channel-directions.go
passed message

下一個範例:選擇器