跳出选择循环?

我正在尝试使用select循环来接收消息或超时信号。如果收到超时信号,循环应该中止:


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)

        }

    }

}

然而,它似乎并没有停止:


$ 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错了吗?


皈依舞
浏览 243回答 3
3回答

呼唤远方

Go规范说:“break”语句终止同一函数内最里面的“for”、“switch”或“select”语句的执行。在您的示例中,您只是脱离了 select 语句。如果您替换break为一条return语句,您将看到它正在运行。

SMILET

在您的示例代码中, areturn似乎像 Pat 所说的那样合适,但为了将来参考,您可以使用标签:package mainimport (&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "time")func main() {&nbsp; &nbsp; done := time.After(1 * time.Millisecond)&nbsp; &nbsp; numbers := make(chan int)&nbsp; &nbsp; // Send to channel&nbsp; &nbsp; go func() {&nbsp; &nbsp; &nbsp; &nbsp; for n := 0; ; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; numbers <- n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; n++&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }()readChannel:&nbsp; &nbsp; for {&nbsp; &nbsp; &nbsp; &nbsp; select {&nbsp; &nbsp; &nbsp; &nbsp; case <-done:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break readChannel&nbsp; &nbsp; &nbsp; &nbsp; case num := <-numbers:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(num)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; // Additional logic...&nbsp; &nbsp; fmt.Println("Howdy")}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go