What restrictions does Go place on goto?
Question 23HardGo 1.22 to 1.25
Go has goto, but with two rules that keep it safe:
- It can't jump over a variable declaration if the variable would be in scope at the label. That would create a variable that was never initialized.
- It can't jump into a block from outside it, for example into an
ifbody or a loop body. Jumping out of blocks is allowed.
func bad1() {
goto end
x := 1 // compile error: goto end jumps over variable declaration
_ = x
end:
fmt.Println("end")
}
func bad2(n int) {
goto inside // compile error: goto inside jumps into block
if n > 0 {
inside:
fmt.Println(n)
}
}
// Legal: declare before the goto, or put the declaration in its own block.
func retry() error {
attempts := 0
again:
if err := try(); err != nil {
attempts++
if attempts < 3 {
goto again
}
return err
}
return nil
}
The standard library uses goto sparingly, for example in math and in generated parsers, for cleanup or state-machine code. What the interviewer wants to hear: you know the rules, and you prefer loops, labeled breaks or helper functions in normal code.
More on Language Fundamentals & Types
- Q21How does initialization work across packages, and what are the rules for
init()? - Q22How do labeled
breakandcontinuework? Why does a plainbreakinsideselectnot leave the loop? - Q24How does
switchdiffer from C, and what does thisfallthroughexample print? - Q25Which types are comparable in Go, and when does comparing values panic at run time?
- Q26How does struct and array equality work? What is surprising about NaN as a map key?
- Q27What does the
comparableconstraint mean in generics, and what changed in Go 1.20?