W3Basic Logo

Go goto statement

The goto statement is go programming acts as a jump statement that alters the normal sequence of the program execution by transferring the control to the labeled statement.


Goto instructions

One of the most controversial features of the Go language is the goto instruction, a way to jump to a labeled statement in the code.

Definition: A labeled statement is a statement that is preceded by a label, which is an identifier followed by a colon. For example:

hello:
	fmt.Println("Hello, world!")

Writing loops without for

Let's say we want to write a function that prints the numbers from 1 to 10. We could write it like this:

func printNumbers() {
	for i := 1; i <= 10; i++ {
		fmt.Println(i)
	}
}

as we have seen before. But it is actually possible to write it without a for loop:

package main

import "fmt"

func printNumbers() {
	i := 1
loop:
	fmt.Println(i)
	i++
	if i <= 5 {
		goto loop
	}
}

func main() {
	printNumbers()

}

Output

1
2
3
4
5

goto loop should be read as "go back to the line where the label loop is". It acts as an alternate to for loop and keeps executing the labeled statement until i <= 5 condition is met.

Skipping parts of the code

Another use of goto is to skip parts of the code if a condition is met, for example, an error.

func doSomeStuff() error {
	// ...
	if err != nil {
		goto cleanup
	}
	// ...
	if err != nil {
		goto cleanup
	}
	// ...
clenaup:
	// ...
}

The idea is that we can jump to the cleanup label if an error occurs, and then we can do the cleanup in one place.

Why is goto controversial?

The problem with goto is that it is very easy to write bad code with it. Indeed it is harder to follow the flow of the program when there are goto instructions than when there are only for loops and if statements.

© 2023 W3Basic. All rights reserved.

Follow Us: