Break and Continue
With break
you can quit loops early. By itself, break
breaks the current loop.
for i := 0; i < 10; i++ {
if i > 5 {
break 1
}
fmt.Println(i) 2
}
Here we break
the current loop 1, and don’t continue with thefmt.Println(i)
statement 2. So we only print 0 to 5. With loops within loopyou can specify a label after break
to identify which loop to stop:
J: for j := 0; j < 5; j++ { 1
for i := 0; i < 10; i++ {
if i > 5 {
break J 2
}
fmt.Println(i)
}
}
Here we define a label “J” 1, preceding the for
-loop there. When we usebreak J
2, we don’t break the inner loop but the “J” loop.
With continue
you begin the next iteration of theloop, skipping any remaining code. In the same way as break
, continue
alsoaccepts a label.
当前内容版权归 Miek Gieben 或其关联方所有,如需对内容或内容相关联开源项目进行关注与资助,请访问 Miek Gieben .