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

Go goto Statement

Go goto Statement

Go Language Loop StatementsGo Language Loop Statements

The goto statement in Go can transfer control unconditionally to a specified line in the procedure.

The goto statement is usually used together with conditional statements. It can be used to implement conditional branching, form loops, jump out of loop bodies, and so on.

However, in structured programming, the use of goto is generally discouraged, to avoid confusing the program flow and making understanding and debugging difficult.

Syntax

The syntax of goto is as follows:

goto label;

..

.

label: statement;

The flowchart of the goto statement is as follows:

Example

When variable a equals 15, skip the current iteration and return to the start of the loop at the LOOP statement:

Example

package

main

import

"fmt"

func

main

()

{

   

/* Define local variables */

   

var

a

int

=

10

   

/* Loop */

   LOOP

:

for

a <

20

{

     

if

a

==

15

{

         

/* Skip the iteration */

         a

=

a

1

         

goto

LOOP

     

}

      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

Go Language Loop StatementsGo Language Loop Statements