Gopher

Goto statement in Golang

Published on 29 March 2020
Last Updated on 29 March 2020

Goto statement provided in Golang is a good idea when none of the provided control flow statement such as if else and for loop do what you want.

Use of Goto statement is usually discouraged if you do not know how to use this statement properly.

Instead of using Goto statement, one can use other statements such as if else and for loop for achieving similar results.

Restrictions on Goto statement

Go language specification states that a Goto statement may not jump over variables coming into scope being declared and it may not jump to other code blocks.

Above restrictions make it difficult to missuses goto statement.

Labels in Golang

Labels are used in break, continue and also in goto statements. Labels are mandatory while using a goto statement.

Scope of a label is the function where the label is declared.

Program to demonstrate how to use Goto statement

Program given below demonstrates how a loop can be created using the Goto statement.

// program to demonstrate use of labels in a Go program
package main

import "fmt"

func main() {
	a := 0
	// label
start:
	a = a + 1
	fmt.Println("a is:", a)
	if a < 4 {
		// goto label if a is less than 4
		goto start
	}

	fmt.Println("program successfully executed")
}

Program output

Above program produces following output:

a is: 1
a is: 2
a is: 3
a is: 4
program successfully executed

Program Description

Above program makes use of labels for creating a loop similar to for loop. In above program, variable a is incremented on every iteration. If value of variable a is less than a then a goto statement is called to jump to the start label. This conditional jump creates a loop that ends when the condition a < 4 is no longer true.