华域联盟 Golang golang 跳出for循环操作

golang 跳出for循环操作

执行以下代码,发现无法跳出for循环:

func SelectTest() {
 i := 0
 for {
 select {
 case <-time.After(time.Second * time.Duration(2)):
 i++
 if i == 5 {
 fmt.Println("跳出for循环")
 }
 }
 fmt.Println("for循环内 i=", i)
 }
 fmt.Println("for循环外")
}

解决办法有两个:

1.使用break:

func SelectTest() {
 i := 0
Loop:
 for {
 select {
 case <-time.After(time.Second * time.Duration(2)):
 i++
 if i == 5 {
 fmt.Println("跳出for循环")
 break Loop
 }
 }
 fmt.Println("for循环内 i=", i)
 }
 fmt.Println("for循环外")
}

2.使用goto:

func SelectTest() {
 i := 0
 for {
 select {
 case <-time.After(time.Second * time.Duration(2)):
 i++
 if i == 5 {
 fmt.Println("跳出for循环")
 goto Loop
 }
 }
 fmt.Println("for循环内 i=", i)
 }
Loop:
 fmt.Println("for循环外")
}

分析:

使用break lable 和 goto lable 都能跳出for循环;不同之处在于:break标签只能用于for循环,且标签位于for循环前面,goto是指跳转到指定标签处

补充:golang跳出for select 循环

通常在for循环中,使用break可以跳出循环,但是注意在go语言中,for select配合时,break并不能跳出循环。

func 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")
}

如下调用:

//尝试2 select for 跳出循环
c := make(chan bool)
go testSelectFor(c)
 
c <- true
c <- false
close(c)
 
time.Sleep(time.Duration(2) * time.Second)

运行结果如下,可以看到break无法跳出循环:

...
close channel 1 false
close channel 1 false
close channel 1 false
close channel 1 false
...

了解决这个问题,需要设置标签,break 标签或goto 便签即可跳出循环,如下两种方法均可。

func 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")
}

同样调用,输出结果如下:

ch2 val = true
ch2 val = false
close channel 2 false
exit testSelectFor2

以上为个人经验,希望能给大家一个参考,也希望大家多多支持华域联盟。如有错误或未考虑完全的地方,望不吝赐教。

本文由 华域联盟 原创撰写:华域联盟 » golang 跳出for循环操作

转载请保留出处和原文链接:https://www.cnhackhy.com/110901.htm

本文来自网络,不代表华域联盟立场,转载请注明出处。

作者: sterben

发表回复

联系我们

联系我们

2551209778

在线咨询: QQ交谈

邮箱: [email protected]

工作时间:周一至周五,9:00-17:30,节假日休息

关注微信
微信扫一扫关注我们

微信扫一扫关注我们