In this tutorial you will learn about the Go Continue Statement and its application with practical example.
Go Continue Statement
The continue statement gives you way to skip over the current iteration of any loop. When a continue statement is encountered in the loop, the Go interpreter ignores rest of statements in the loop body for current iteration and returns the program execution to the very first statement in the loop body. It does not terminates the loop rather continues with the next iteration.
Syntax:-
1 2 3 4 5 6 7 |
for <condition1> { // loop body if (condition2) { continue } // loop body } |
Example:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
package main import "fmt" func main() { var ctr = 0 fmt.Println("W3Adda - Go continue statement.") for ctr < 10 { ctr++ if (ctr == 5) { println("5 is skipped") continue println("This won't be printed too.") } fmt.Printf("Number is %d\n", ctr) } fmt.Println("Out of loop") } |
Output:-
As you can see when ctr == 5, continue statement is executed which causes the current iteration to end and the control moves on to the next iteration.
Go Labeled continue
The standard unlabeled continue statement is used to skip the current iteration of nearest enclosing loop. In GoLang, there is another form of continue (labeled continue ) statement is used to skip iteration of specified loop (can be outer loop). In Golang, Label is an identifier which is followed by colon (:) sign, for example abc:, test:.
Example:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
package main import "fmt" func main() { var i = 0 var j = 0 fmt.Println("W3Adda - Go continue statement.") outerfor: for i < 3 { j = 0 i++ for j < 3 { j++ fmt.Printf("i is %d and j is %d\n",i,j) if(i == 2){ fmt.Println("I am Skipped") continue outerfor } fmt.Println("I am Printed") } } } |
Output:-
Here, when i == 2 expression is evaluated to true, continue outerfor is executed which skips the current iteration of the enclosed loop and return control to the loop marked with label outerfor: