3
以下是選擇的一個示例代碼。我不明白爲什麼第二個選擇不執行第一個案例?輸出似乎是:在頻道中選擇
messages := make(chan string)
signals := make(chan bool)
// Here's a non-blocking receive. If a value is
// available on `messages` then `select` will take
// the `<-messages` `case` with that value. If not
// it will immediately take the `default` case.
select {
case msg := <-messages:
fmt.Println("received message", msg)
default:
fmt.Println("no message received")
}
// A non-blocking send works similarly.
msg := "hi"
select {
case messages <- msg:
fmt.Println("sent message", msg)
default:
fmt.Println("no message sent")
}
// We can use multiple `case`s above the `default`
// clause to implement a multi-way non-blocking
// select. Here we attempt non-blocking receives
// on both `messages` and `signals`.
select {
case msg := <-messages:
fmt.Println("received message", msg)
case sig := <-signals:
fmt.Println("received signal", sig)
default:
fmt.Println("no activity")
}
後,我運行的代碼,輸出:
no message received
no message sent
no activity
更新:我知道爲什麼第二次選擇去現在爲默認值。第三個呢?
謝謝,那麼下一個呢?我們已經將消息推送給消息。第一種情況應該執行,爲什麼仍然是默認的? – WhatABeautifulWorld
您還沒有將'msg'發送給'messages'。該發送不會執行,因爲它會阻止;這就是爲什麼從這種情況下打印的文本是「沒有消息發送」。 – twotwotwo