Go

What are the rules for := redeclaration, and why does this not compile?

Question 7HardGo 1.22 to 1.25
func parse(s string) (n int, err error) {
	if s != "" {
		n, err := strconv.Atoi(s)
		if err != nil {
			return // compile error: result parameter err not in scope at return
		}
		_ = n
	}
	return
}

:= can redeclare a variable only if three things are true: at least one variable on the left is new, the redeclared variable was declared in the same scope, and it keeps the same type. If so, the existing variable is simply assigned. Here, though, the if block is a new scope. So n and err are brand-new variables that hide the named results. A bare return would return the outer results, which have not been set. The compiler catches exactly this mistake and refuses to compile it.

Other rules:

  • a, b := 1, 2 followed by a, b := 3, 4 in the same scope is an error: "no new variables on left side of :=".
  • := is not allowed at package level. There you must use var.
  • You can't use := to assign to a struct field or an index expression (s.f, err := ... is invalid).

What the interviewer wants to hear: in functions with named results, use = inside nested blocks, or return explicit values.

More on Language Fundamentals & Types

All 39 Language Fundamentals & Types questions