Go

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:

  1. 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.
  2. It can't jump into a block from outside it, for example into an if body 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

All 39 Language Fundamentals & Types questions