Most programs written in the Go language use methods to control flow: when a method exits, control returns to its calling location. But the goto
keyword can be used to move within a method.
With goto
, we need to specify a matching label that is at the same level of scope, or a higher scope. So we can move out of an if
-statement, but not into one.
This program converts a string
into an integer with strconv.Atoi
, then tests it with an if
-statement. It then uses goto
within the main method.
string
literal containing the text "100" and convert it into the integer 100.if
-statement. Each branch of the if
-statement contains a goto
statement.goto
NotOneHundred
statement, we will print this message—but in the example program, this code is not reached.goto
IsOneHundred
, so we print the message "Is one hundred" here.package main
import (
"fmt"
"strconv"
)
func main() {
// Part 1: parse in a value from a string.
value, _ := strconv.Atoi("100")
fmt.Println(value)
// Part 2: test the value, and if it is is 100, use goto to a certain label.
if value == 100 {
goto IsOneHundred
} else {
goto NotOneHundred
}
// Part 3: this is not reached, but it can handle the NotOneHundred case.
NotOneHundred:
fmt.Println("Not one hundred")
return
// Part 4: with goto, we reach here but never print the previous message.
IsOneHundred:
fmt.Println("Is one hundred")
}100
Is one hundred
Most Go programs will benefit from having no goto
statements—the goto
tends to lead to confusing code. But occasionally, code that is generated or unusual may be benefit from a goto
.