1 回答

TA贡献2016条经验 获得超9个赞
编辑:你编辑了你的代码,所以这里是编辑后的答案。
要从内部继续外循环(打破内循环并跳过外循环的其余部分),您必须继续外循环。
要使用语句解决外部循环,请continue使用标签:
outer:
for i := 0; i < 2; i++ {
for j := 0; j < 4; j++ {
if j == 2 {
fmt.Println("Breaking out of loop")
continue outer
} else {
fmt.Println("j = ", j)
}
}
fmt.Println("The value of i is", i)
}
这将输出(在Go Playground上尝试):
j = 0
j = 1
Breaking out of loop
j = 0
j = 1
Breaking out of loop
原答案:
break总是从最内层循环中断(更具体地说是 a或) for,因此之后外层循环将继续其下一次迭代。switchselect
如果您有嵌套循环,并且您想从外部循环中断内部循环,则必须使用标签:
outer:
for i := 0; i < 2; i++ {
for j := 0; j < 4; j++ {
if j == 2 {
fmt.Println("Breaking out of loop")
break outer
}
fmt.Println("The value of j is", j)
}
}
这将输出(在Go Playground上尝试):
The value of j is 0
The value of j is 1
Breaking out of loop
- 1 回答
- 0 关注
- 104 浏览
添加回答
举报