預設情況下,通道是未緩衝的,意味著如果有相應的接收(<- chan
)準備好接收傳送的值,它們將只接受傳送(chan <-
)。 緩衝通道接受有限數量的值,而沒有用於這些值的相應接收器。
這裡使一個字串的通道緩衝多達2
個值。因為這個通道被緩衝,所以可以將這些值傳送到通道中,而沒有相應的並行接收。
之後可以照常接收這兩個值。
所有的範例程式碼,都放在
F:\worksp\golang
目錄下。安裝Go程式設計環境請參考:/2/23/798.html
channel-buffering.go
的完整程式碼如下所示 -
package main
import "fmt"
func main() {
// Here we `make` a channel of strings buffering up to
// 2 values.
messages := make(chan string, 2)
// Because this channel is buffered, we can send these
// values into the channel without a corresponding
// concurrent receive.
messages <- "buffered"
messages <- "channel"
// Later we can receive these two values as usual.
fmt.Println(<-messages)
fmt.Println(<-messages)
}
執行上面程式碼,將得到以下輸出結果 -
F:\worksp\golang>go run channel-buffering.go
buffered
channel