0
0
GoHow-ToBeginner · 3 min read

How to Use goto in Go: Syntax, Example, and Tips

In Go, goto lets you jump to a labeled statement within the same function. Use goto labelName to jump, and define the label with labelName:. It helps control flow but should be used sparingly to keep code clear.
📐

Syntax

The goto statement transfers control to a labeled statement within the same function. The label is defined by a name followed by a colon (labelName:), and the jump is made using goto labelName.

  • goto: keyword to jump
  • labelName: defines the target location
  • Labels must be in the same function
go
func example() {
    fmt.Println("Start")
    goto skip
    fmt.Println("This will be skipped")
skip:
    fmt.Println("After goto")
}
💻

Example

This example shows how goto skips a print statement and jumps to the labeled line.

go
package main

import "fmt"

func main() {
    fmt.Println("Step 1")
    goto skipStep
    fmt.Println("Step 2 - skipped")
skipStep:
    fmt.Println("Step 3 - after goto")
}
Output
Step 1 Step 3 - after goto
⚠️

Common Pitfalls

Using goto can make code hard to read if overused or used to jump backward creating loops. It cannot jump outside the current function or into blocks like loops or conditionals improperly. Avoid jumping into variable declarations or skipping initialization.

Wrong use example:

func wrong() {
    goto label
    var x = 5 // This declaration is skipped, causing error
label:
    fmt.Println("Hello")
}

Correct use moves label after declarations:

func correct() {
    var x = 5
label:
    fmt.Println("Hello", x)
}
📊

Quick Reference

  • Use goto only for simple jumps within a function.
  • Labels must be unique and end with a colon.
  • Do not jump into loops, conditionals, or skip variable declarations.
  • Prefer structured control flow (if, for, switch) over goto for clarity.

Key Takeaways

Use goto to jump to a labeled statement within the same function only.
Define labels with a name followed by a colon, like labelName:.
Avoid jumping over variable declarations or into blocks like loops or conditionals.
Overusing goto can make code confusing; prefer structured control flow.
Labels must be unique and visible only inside the function where they are declared.