Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Go Language continue Statement

Go Language continue Statement

Go Language Loop StatementsGo Language Loop Statements

Go's continue statement is somewhat similar to the break statement. But continue does not jump out of the loop; instead it skips the current iteration and proceeds to the next one.

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

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

Syntax

The syntax of continue is as follows:

continue;

The flow chart of the continue statement is as follows:

Example

Skip the current iteration and proceed to the next when variable a equals 15:

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 example above produces:



a 的值为 : 10

a 的值为 : 11

a 的值为 : 12

a 的值为 : 13

a 的值为 : 14

a 的值为 : 16

a 的值为 : 17

a 的值为 : 18

a 的值为 : 19

The following example has multiple loops and demonstrates the difference between using 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

           

}

   

}

   

// With 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 example above produces:



---- 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 StatementsGo Language Loop Statements