Goto statements

August 21, 2024

We’ve finished the discussion of the new range-over-func feature, so let’s continue where we left off before the Go 1.23 release, with a feature you’ll rarely, if ever, use.

Goto statements

A “goto” statement transfers control to the statement with the corresponding label within the same function.

GotoStmt = "goto" Label .
goto Error

Unless your only programming experience has been in the BASIC language, you’ve probably learned to eschew “goto”. We all know by now that Goto is considered harmful, right? Many modern languages don’t even have this feature at all!

So why does Go have it?

Well, there are certain cases where goto can be more performant, or even, dare I say, more readable, than alternatives. These situations are somewhat rare, but they do exist.

Further, Go’s goto, is fairly restrictive, as we’ll now see. Much more so than BASIC’s, if you’ve ever used that.

Executing the “goto” statement must not cause any variables to come into scope that were not already in scope at the point of the goto. For instance, this example:

	goto L  // BAD
	v := 3
L:

is erroneous because the jump to label L skips the creation of v.

A “goto” statement outside a block cannot jump to a label inside that block. For instance, this example:

if n%2 == 1 {
	goto L1
}
for n > 0 {
	f()
	n--
L1:
	f()
	n--
}

is erroneous because the label L1 is inside the “for” statement’s block but the goto is not.

So, unlike in BASIC, you cannot simply goto any location in your program. You can only jump over variable declarations, and you cannot jump into blocks–only out of them. This may not seem like that much, but it really is quite restrictive. It means you can’t goto between functions, for example.

Go’s goto doesn’t so much let you jump around, as make small hops around.

So when should you use goto?

My advice, when in doubt: Don’t.

By the time you’re in a situation where goto is warranted, I suspect you’ll have enough experience to justify the use of it.

Quotes from The Go Programming Language Specification Language version go1.23 (June 13, 2024)


Share this

Direct to your inbox, daily. I respect your privacy .

Unsure? Browse the archive .

Get daily content like this in your inbox!

Subscribe