Skip to content
Tutorials Center
My learning

Topics

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.

Go
i := 0
retry:
    i++
    if i < 3 {
        goto retry
    }

Try it

Go A retry loop with goto

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.

Go Jumping out of nested blocks

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

Go
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 L must not cause any variable to come into scope that was not already in scope at the goto. So this is an error: a goto that skips x := 1 when x is still in scope at label L. Put the variable in an inner block or declare it before the jump.
  • No jumping into blocks. A goto outside a block cannot target a label inside that block (if, for, switch or { }). Jumping out of blocks is fine.
  • Unused labels are errors. A label that is never referenced by goto, break or continue makes the program fail to compile with "label defined and not used".
  • Labeled break and continue are usually a clearer way to leave nested loops. Reach for break with a label first.
  • Error cleanup. Some code uses goto cleanup at the end of a function, as in C. In Go, defer usually does this job better.
  • Standard library. The library uses goto rarely, mostly in performance-sensitive parsers and generated code.
  • No computed gotos. The target is always a plain label, never a variable.