Introduction
The continue
statement in Go is used to skip the remaining code in the current iteration of a loop and immediately start the next iteration. It allows you to bypass certain parts of the loop body when specific conditions are met, effectively controlling the flow of the loop. In this chapter, you will learn the syntax and usage of the continue
statement in Go, with examples to illustrate how it works.
Syntax
The continue
statement can be used within loops (for
) to skip to the next iteration of the loop.
Syntax:
continue
Examples
continue in a For Loop
The continue
statement can be used to skip certain iterations of a for
loop when a condition is met.
Example:
package main
import "fmt"
func main() {
for i := 0; i < 10; i++ {
if i%2 == 0 {
continue // Skip even numbers
}
fmt.Println(i) // Output: 1 3 5 7 9
}
}
continue in a Nested Loop
When used in nested loops, the continue
statement only affects the nearest enclosing loop.
Example:
package main
import "fmt"
func main() {
for i := 0; i < 3; i++ {
for j := 0; j < 3; j++ {
if j == 1 {
continue // Skip the rest of the inner loop when j == 1
}
fmt.Printf("i: %d, j: %d\n", i, j)
}
}
}
Using continue with Labels
You can use labels to control which loop the continue
statement should affect when dealing with nested loops.
Example:
package main
import "fmt"
func main() {
outer:
for i := 0; i < 3; i++ {
for j := 0; j < 3; j++ {
if i == 1 && j == 1 {
continue outer // Skip the rest of the outer loop's current iteration when i == 1 and j == 1
}
fmt.Printf("i: %d, j: %d\n", i, j)
}
}
}
Conclusion
The continue
statement in Go is a useful control structure that allows you to skip the remainder of the current iteration of a loop and proceed with the next iteration. It is particularly helpful for bypassing certain parts of the loop body based on specific conditions. By understanding how to use the continue
statement, you can better manage the flow of your loops and write more efficient and readable code.