【轉】golang for select 循環跳出


原文:https://blog.csdn.net/bravezhe/article/details/81674591

---------------------------------------------------------

golang for select 循環跳出
原創墨子哲 發布於2018-08-14 21:10:30 閱讀數 4194 收藏
展開
執行以下代碼,發現無法跳出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是指跳轉到指定標簽處
————————————————
版權聲明:本文為CSDN博主「墨子哲」的原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/bravezhe/article/details/81674591


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM