跳出选择循环? [英] Break out of select loop?
本文介绍了跳出选择循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在循环中使用 select
来接收消息或超时信号.如果收到超时信号,则循环应中止:
I'm trying to use a select
in a loop to receive either a message or a timeout signal. If the timeout signal is received, the loop should abort:
package main
import ("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)
}
}
}
但是,它似乎并没有停止:
However, it doesn't seem to be stopping:
$ go run a.go
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
[...]
3824
3825
[...]
为什么?我在 time.After
之后使用错误吗?
Why? Am I using time.After
wrong?
推荐答案
围棋规范说:
"break"语句终止最里面的"for"的执行,同一功能内的"switch"或"select"语句.
A "break" statement terminates execution of the innermost "for", "switch", or "select" statement within the same function.
在您的示例中,您只是打破了select语句.如果将 break
替换为 return
语句,您将看到它正在工作.
In your example you're just breaking out of the select statement. If you replace break
with a return
statement you will see that it's working.
这篇关于跳出选择循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文