Home
Go
goto Keyword Example
Updated Jan 29, 2025
Dot Net Perls
Goto. 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.
if
Example. 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.
strconv
Part 1 We parse a string literal containing the text "100" and convert it into the integer 100.
Part 2 We test the value with an if-statement. Each branch of the if-statement contains a goto statement.
Part 3 If we reached the goto NotOneHundred statement, we will print this message—but in the example program, this code is not reached.
Part 4 In the program, we execute 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
Summary. 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.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Jan 29, 2025 (new).
Home
Changes
© 2007-2025 Sam Allen