« Back to Index

Go: the goto statement

View original Gist on GitHub

Tags: #go

main.go

// https://play.golang.com/p/EAtzwpDeb30
// https://go.dev/ref/spec#Goto_statements

package main

import (
	"fmt"
)

func main() {
	goTo("beep")
	goTo("boop")
	goTo("xxxx")
}

func goTo(location string) {
	switch location {
	case "beep":
		goto beep
	case "boop":
		goto boop
	default:
		fmt.Println("unrecognised location")
		return
	}

beep:
	fmt.Println("beep was reached")
	return // IMPORTANT: Go will continue to execute the following code, so return to avoid accidentally printing "boop was reached"
boop:
	fmt.Println("boop was reached")
	return
}