Go language continue statement

Go language loop statements

Go's continue statement is somewhat like the break statement. However, continue does not break out of the loop, but skips the current iteration and executes the next loop iteration.

In a for loop, executing a continue statement triggers the execution of the for increment statement.

In nested loops, you can use a label to mark the loop you want to continue.

Syntax

The continue syntax format is as follows:

continue;

The continue statement flowchart is as follows:

Example

When variable a equals 15, skip the current loop iteration and execute the next loop iteration:

Example

package main

import "fmt"

func main() {
   /* Define local variables */
   var a int = 10

   /* for loop */
   for a < 20 {
      if a == 15 {
         /* skip this iteration */
         a = a + 1;
         continue;
      }
      fmt.Printf("The value of a is : %d\n", a);
      a++;    
   }  
}

The execution result of the above example is:

a 的值为 : 10
a 的值为 : 11
a 的值为 : 12
a 的值为 : 13
a 的值为 : 14
a 的值为 : 16
a 的值为 : 17
a 的值为 : 18
a 的值为 : 19

The following example has multiple loops, demonstrating the difference between using a label and not using a label.

Example

package main

import "fmt"

func main() {

    // without a label
    fmt.Println("---- continue ---- ")
    for i := 1; i <= 3; i++ {
        fmt.Printf("i: %d\n", i)
            for i2 := 11; i2 <= 13; i2++ {
                fmt.Printf("i2: %d\n", i2)
                continue
            }
    }

    // using a label
    fmt.Println("---- continue label ----")
    re:
        for i := 1; i <= 3; i++ {
            fmt.Printf("i: %d\n", i)
                for i2 := 11; i2 <= 13; i2++ {
                    fmt.Printf("i2: %d\n", i2)
                    continue re
                }
        }
}

The execution result of the above example is:

---- continue ---- 
i: 1
i2: 11
i2: 12
i2: 13
i: 2
i2: 11
i2: 12
i2: 13
i: 3
i2: 11
i2: 12
i2: 13
---- continue label ----
i: 1
i2: 11
i: 2
i2: 11
i: 3
i2: 11

Go language loop statements

other extensions