我正在嘗試使用select循環來接收消息或超時信號。如果收到超時信號,循環應該中止:package mainimport ("fmt"; "time")func main() { done := time.After(1*time.Millisecond) numbers := make(chan int) go func() {for n:=0;; {numbers <- n; n++}}() for { select { case <-done: break case num := <- numbers: fmt.Println(num) } }}然而,它似乎并沒有停止:$ go run a.go01234567891011121314151617181920212223242526272829303132[...]38243825[...]為什么?我用time.After錯了嗎?
3 回答

SMILET
TA貢獻1796條經驗 獲得超4個贊
在您的示例代碼中, areturn似乎像 Pat 所說的那樣合適,但為了將來參考,您可以使用標簽:
package main
import (
"fmt"
"time"
)
func main() {
done := time.After(1 * time.Millisecond)
numbers := make(chan int)
// Send to channel
go func() {
for n := 0; ; {
numbers <- n
n++
}
}()
readChannel:
for {
select {
case <-done:
break readChannel
case num := <-numbers:
fmt.Println(num)
}
}
// Additional logic...
fmt.Println("Howdy")
}
- 3 回答
- 0 關注
- 285 瀏覽
添加回答
舉報
0/150
提交
取消