Go Reference ยท Keywords and Statements
The goto statement
Reference for Go goto: jump to a label in the same function, the rules about skipped variable declarations and blocks, and the rare cases where it is useful.
goto transfers control to a labeled statement in the same function. It exists for completeness and a few special cases, such as generated code or retry logic in low-level routines. Most Go code never uses it, because loops, break, continue and defer cover the usual needs.
The compiler restricts goto so that jumps cannot create confusing situations: you may not jump over a variable declaration that is still in scope at the label, and you may not jump into a block.
i := 0 retry: i++ if i < 3 { goto retry }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Syntax
GotoStmt = "goto" Label . LabeledStmt = Label ":" Statement .
| Part | Description |
|---|---|
Label |
An identifier declared in the same function. Labels have function scope and their own namespace, so a label can share a name with a variable. |
Usage notes
- No jumping over declarations. Executing
goto Lmust not cause any variable to come into scope that was not already in scope at thegoto. So this is an error: agotothat skipsx := 1whenxis still in scope at labelL. Put the variable in an inner block or declare it before the jump. - No jumping into blocks. A
gotooutside a block cannot target a label inside that block (if,for,switchor{ }). Jumping out of blocks is fine. - Unused labels are errors. A label that is never referenced by
goto,breakorcontinuemakes the program fail to compile with "label defined and not used". - Labeled
breakandcontinueare usually a clearer way to leave nested loops. Reach forbreakwith a label first. - Error cleanup. Some code uses
goto cleanupat the end of a function, as in C. In Go,deferusually does this job better. - Standard library. The library uses
gotorarely, mostly in performance-sensitive parsers and generated code. - No computed gotos. The target is always a plain label, never a variable.