Goto statement

Goto statement is used to go or jump to a labeled statement in the same function.

In this tutorial, we will learn the syntax of goto statement and how to use it with the help of a few example scenarios.

Syntax

The syntax of goto statement is

goto label
//statement(s)
label: statement

or

label: statement
//statement(s)
goto label
ADVERTISEMENT

Examples

In the following program, we use goto statement with label x.

example.go

package main

import (
	"fmt"
)

func main() {
	fmt.Println("Apple")
	goto x
	fmt.Println("Banana")
x:
	fmt.Println("Cherry")
}

Output

Apple
Cherry

In the following program, we use goto statement to jump to outer for loop from inner for loop. We print a start pattern, of course.

example.go

package main

import "fmt"

func main() {
	i := 0
x:
	for ; i < 5; i++ {
		for k := 0; k < 5; k++ {
			if k == i {
				i++
				fmt.Println()
				goto x
			}
			fmt.Print("  *")
		}
	}
}

Output

*
  *  *
  *  *  *
  *  *  *  *

Conclusion

In this Golang Tutorial, we learned what a goto statement is in Go language, and how to use it with the help of example programs.