Example. 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.
Here When an element in the 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
Label. 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.
Part 1 We have a named label called Outer to refer to the outer of the 2 loops in the program.
Part 2 When both loop iteration variables are equal to 1, we skip further iterations of the inner loop, and continue iterating the outer loop.
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
Summary. 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.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.