A for
-loop keeps iterating until it reaches a terminating condition. Unlike break
, continue will just stop the current iteration of a loop.
With a label, we can even use continue to go to the next iteration of an enclosing loop. This can lead to clearer Go code that is easier to maintain.
Here we use the continue
-keyword in a for
-loop. Continue ends the current iteration of a loop, but then the next iteration begins as usual—the loop itself is not terminated.
int
slice equals 10, we use continue to stop processing of the current iteration.package main import "fmt" func main() { elements := []int{10, 20} for i := range elements { // If element is 10, continue to next iteration. if elements[i] == 10 { fmt.Println("CONTINUE") continue } fmt.Println("ELEMENT:", elements[i]) } }CONTINUE ELEMENT: 20
We can use a named label to specify what enclosing loop we want to continue next. The current loop is exited, and the target loop has its next iteration.
package main import "fmt" func main() { // Part 1: a named label outside of 2 nested for-loops. Outer: for i := range 3 { fmt.Println("--") for x := range 3 { fmt.Println(i, x) // Part 2: stop the inner loop and go to the next iteration of the outer loop. if i == 1 && x == 1 { continue Outer } } } }-- 0 0 0 1 0 2 -- 1 0 1 1 -- 2 0 2 1 2 2
Continue can be used to skip to the next iteration of the current loop. And with a label, it can continue to the next iteration of an enclosing loop.