Go Continue Statement

In Go, the continue statement is used to skip the rest of the current iteration of a loop and move to the next iteration. It allows you to control the flow within a loop and selectively skip certain iterations based on a condition. Here are some examples of using the continue statement in Go:

  1. Skipping specific iterations based on a condition:
for i := 0; i < 5; i++ {
    if i == 2 || i == 4 {
        continue
    }
    fmt.Println(i)
}

In this example, the loop iterates from 0 to 4. However, when i is equal to 2 or 4, the continue statement is encountered, and the current iteration is skipped. The loop then proceeds to the next iteration. The output will be:

0
1
3
  1. Skipping iterations in a nested loop:
for i := 0; i < 3; i++ {
    for j := 0; j < 3; j++ {
        if j == 1 {
            continue
        }
        fmt.Println(i, j)
    }
}

In this example, there is a nested loop structure. When j is equal to 1, the continue statement is encountered, causing the current iteration of the inner loop to be skipped. The inner loop then moves to the next iteration. The output will be:

0 0
0 2
1 0
1 2
2 0
2 2

The continue statement allows you to selectively skip certain iterations of a loop while continuing with the next iteration. It provides fine-grained control over the loop execution and can be useful in scenarios where you need to skip specific iterations based on certain conditions.