To go-goto or not to go-goto
I once inherited an awful mess of VB6 code, still a bit of shivers thinking of it..
A too common pattern was:
on error goto hell
In a way a bit fitting. using goto has lead to spaghetti code or goto hell.
Is it pure evil to use it? Not really, but the use case must be very solid. One modern big coding language now is go from google, so how is used there?
Go has a goto statement. It's rarely used, but it exists — and the standard library uses it in a few specific patterns. Here are three real-world examples where it makes sense.
1. Basic loop with goto
A simple labeled loop — goto jumps back to the label unconditionally, and the if decides when to stop:
func main() {
i := 0
loop:
fmt.Println(i)
i++
if i < 3 {
goto loop
}
}
2. Common exit point (runtime/select.go pattern)
Multiple code paths converging to a single cleanup label — avoids duplicating cleanup code at every exit point:
func sellock(scases []scase, lockorder []uint16) {
// ... various code paths ...
goto retc
bufrecv:
// ...
goto retc
bufsend:
// ...
goto retc
recv:
// ...
goto retc
retc:
if caseReleaseTime > 0 {
// common cleanup
}
}
3. Skipping code blocks (go/scanner pattern)
The scanner uses goto exit to bypass the multiline-comment parser when it only has a single-line comment — avoids nested if flags:
func (s *Scanner) scanComment() string {
if s.ch == '/' {
// single-line comment
s.next()
for s.ch != '\n' && s.ch >= 0 {
s.next()
}
goto exit // skip the multiline parser entirely
}
/*-style comment */
s.next()
for s.ch >= 0 {
ch := s.ch
s.next()
if ch == '*' && s.ch == '/' {
s.next()
goto exit // skip the error below
}
}
s.error(offs, "comment not terminated")
exit:
// common post-processing
return string(lit)
}
Go's goto is restrictive — you can't jump into blocks or skip variable declarations — which prevents the worst spaghetti-code abuses. In application code you'll rarely need it, but in the standard library it shows up in parsers, runtime code, and hot paths where defer overhead matters.
Before putting goto in normal code, make sure you are really awake..
So listen to the song in the hero before deciding!