通道是連接并發(fā)goroutine的管道??梢詮囊粋€(gè)goroutine向通道發(fā)送值,并在另一個(gè)goroutine中接收到這些值。
使用make(chan val-type)創(chuàng)建一個(gè)新通道,通道由輸入的值傳入。使用通道 <- 語法將值發(fā)送到通道。 這里從一個(gè)新的goroutine發(fā)送“ping”到在上面的消息通道。
<-channel語法從通道接收值。在這里,將收到上面發(fā)送的“ping”消息并打印出來。當(dāng)運(yùn)行程序時(shí),“ping”消息通過通道成功地從一個(gè)goroutine傳遞到另一個(gè)goroutine。默認(rèn)情況下發(fā)送和接收塊,直到發(fā)送方和接收方都準(zhǔn)備好。此屬性允許在程序結(jié)束時(shí)等待“ping”消息,而不必使用任何其他同步。
所有的示例代碼,都放在
F:\worksp\golang目錄下。安裝Go編程環(huán)境請(qǐng)參考:http://www.yiibai.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)
}
執(zhí)行上面代碼,將得到以下輸出結(jié)果 -
F:\worksp\golang>go run channels.go
ping