Home »
Golang
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.
- What does the
goto statement do?
- Can a label used with
goto be a variable?
- Where must the label be defined for
goto to work?
Advertisement
Advertisement