我是靠谱客的博主 虚心飞鸟,这篇文章主要介绍golang跳出for select 循环,需要break配合标签才行通常在for循环中,使用break可以跳出循环,但是注意在go语言中,for select配合时,break并不能跳出循环。,现在分享给大家,希望可以做个参考。
通常在for循环中,使用break可以跳出循环,但是注意在go语言中,for select配合时,break并不能跳出循环。
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13func testSelectFor(chExit chan bool){ for { select { case v, ok := <-chExit: if !ok { fmt.Println("close channel 1", v) break } fmt.Println("ch1 val =", v) } } fmt.Println("exit testSelectFor") }
如下调用:
复制代码
1
2
3
4
5
6
7
8
9//尝试2 select for 跳出循环 c := make(chan bool) go testSelectFor(c) c <- true c <- false close(c) time.Sleep(time.Duration(2) * time.Second)
运行结果如下,可以看到break无法跳出循环:
复制代码
1
2
3
4
5
6... close channel 1 false close channel 1 false close channel 1 false close channel 1 false ...
为了解决这个问题,需要设置标签,break 标签或goto 便签即可跳出循环,如下两种方法均可。
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16func testSelectFor2(chExit chan bool){ EXIT: for { select { case v, ok := <-chExit: if !ok { fmt.Println("close channel 2", v) break EXIT//goto EXIT2 } fmt.Println("ch2 val =", v) } } //EXIT2: fmt.Println("exit testSelectFor2") }
同样调用,输出结果如下:
复制代码
1
2
3
4ch2 val = true ch2 val = false close channel 2 false exit testSelectFor2
最后
以上就是虚心飞鸟最近收集整理的关于golang跳出for select 循环,需要break配合标签才行通常在for循环中,使用break可以跳出循环,但是注意在go语言中,for select配合时,break并不能跳出循环。的全部内容,更多相关golang跳出for内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复