How to Use Continue in Go: Syntax and Examples
In Go, the
continue statement skips the rest of the current loop iteration and moves to the next iteration immediately. It works inside for loops and can be used with labels to continue outer loops.Syntax
The continue statement can be used simply as continue to skip to the next iteration of the innermost loop. Optionally, you can use continue label to skip to the next iteration of a labeled outer loop.
- continue: Skips the rest of the current loop iteration.
- continue label: Skips to the next iteration of the loop identified by
label.
go
for i := 0; i < 5; i++ { if i == 2 { continue } fmt.Println(i) } // Using label outer: for i := 0; i < 3; i++ { for j := 0; j < 3; j++ { if j == 1 { continue outer } fmt.Println(i, j) } }
Example
This example shows how continue skips printing the number 2 in a loop from 0 to 4. It also demonstrates using a label to skip inner loop iterations and continue the outer loop.
go
package main import "fmt" func main() { fmt.Println("Simple continue example:") for i := 0; i < 5; i++ { if i == 2 { continue // skip when i is 2 } fmt.Println(i) } fmt.Println("\nContinue with label example:") outer: for i := 0; i < 3; i++ { for j := 0; j < 3; j++ { if j == 1 { continue outer // skip to next iteration of outer loop } fmt.Println(i, j) } } }
Output
Simple continue example:
0
1
3
4
Continue with label example:
0 0
1 0
2 0
Common Pitfalls
One common mistake is using continue outside of loops, which causes a compile error. Another is misunderstanding that continue only skips the current iteration, not the entire loop. Also, forgetting to use labels when trying to continue outer loops can lead to unexpected behavior.
Example of wrong and right usage:
go
package main
func main() {
// Wrong: continue outside loop (uncomment to see error)
// continue
// Wrong: trying to continue outer loop without label
for i := 0; i < 2; i++ {
for j := 0; j < 2; j++ {
if j == 1 {
// continue // This continues inner loop, not outer
}
}
}
// Right: use label to continue outer loop
outer:
for i := 0; i < 2; i++ {
for j := 0; j < 2; j++ {
if j == 1 {
continue outer
}
}
}
}Quick Reference
- continue: Skip to next iteration of current loop.
- continue label: Skip to next iteration of labeled outer loop.
- Only valid inside loops.
- Does not exit the loop, just skips current iteration.
Key Takeaways
Use
continue inside loops to skip the rest of the current iteration.Use labeled
continue to skip iterations of outer loops.continue does not exit the loop, it only skips to the next iteration.Never use
continue outside of loops; it causes errors.Remember to use labels when you want to continue outer loops from inner loops.