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, 2followed bya, b := 3, 4in the same scope is an error: "no new variables on left side of :=".:=is not allowed at package level. There you must usevar.- 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
- Q5What is the difference between a typed and an untyped constant when you assign or compare it?
- Q6Explain variable shadowing. Find the bug in this code.
- Q8What does this print? (Assignment evaluation order)
- Q9What is the difference between a type conversion and a type assertion?
- Q10In a type switch, what is the type of the bound variable when a case lists several types, and how does
case nilbehave? - Q11How are strings represented in Go? What does this print?