×

Go Tutorial

Go Basics

Go Variables

Go Literals

Go Type Handling

Go Operators

Go Decision Making

Go Loops

Go Functions

Go String

Go Arrays

Go Slices

Go Maps

Go Pointers

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Go Goto Statement

Last Updated : July 19, 2025

In Go, the goto statement provides an unconditional jump from the goto statement to a labeled statement within the same function.

Syntax of goto Statement

The general syntax of a goto statement is:

goto labelName
...
labelName:
    // statements to execute

Basic Example of goto

This example demonstrates a basic usage of the goto statement:

package main
import "fmt"

func main() {
    fmt.Println("Before goto")

    goto skip

    fmt.Println("This line is skipped")

skip:
    fmt.Println("After goto")
}

When you run the above code, the output will be:

Before goto
After goto

Using goto to Exit a Loop

The goto statement can be used to break out of nested loops or skip parts of code based on certain conditions.

Example

This example uses goto to exit nested loops when a specific condition is met:

package main
import "fmt"

func main() {
    for i := 1; i <= 3; i++ {
        for j := 1; j <= 3; j++ {
            if i == 2 && j == 2 {
                goto end
            }
            fmt.Printf("i=%d, j=%d\n", i, j)
        }
    }

end:
    fmt.Println("Exited the loop using goto")
}

When you run the above code, the output will be:

i=1, j=1
i=1, j=2
i=1, j=3
i=2, j=1
Exited the loop using goto

Rules for Using goto

  • The label must be defined in the same function.
  • Labels cannot be variables - they must be fixed identifiers followed by a colon.
  • goto should be avoided when it makes the code harder to read or understand.

Best Practices

Although goto can be used in Go, it is best used sparingly. Structured programming with loops and functions is generally more readable and maintainable.

Exercise

Select the correct answers to test your understanding of the goto statement in Go.

  1. What does the goto statement do?
  2. Can a label used with goto be a variable?
  3. Where must the label be defined for goto to work?

Advertisement
Advertisement

Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement

Copyright © 2025 www.includehelp.com. All rights reserved.