Go core · 3 MIN READ
Read a declaration one scope at a time
Follow values through a short declaration, an assignment and a shadowed name without running the program.
A useful way to read Go is to ask three questions at each assignment: which block owns this name, what type does it have, and is a new variable being created? The spelling of a name alone does not answer any of them.
Trace the original variable
Start with a local variable. Its type comes from the expression on the right. An ordinary assignment updates that same variable; it does not create another binding. Read the two lines as a small state table: first count is 2, then count is 5.
count := 2
count = count + 3
fmt.Println(count) // 5The right side is evaluated before the assignment. The old count contributes 2, the expression becomes 5, and only then is count updated. This is useful when stepping through a counter, an index or a retry budget.
A nested block owns a different name
An if body is a new lexical block. A short declaration there may hide an outer variable. This can be intentional for a temporary result, but it becomes confusing when the outer result was supposed to change.
name := "outside"
if ok {
name := "inside"
fmt.Println(name) // inside
}
fmt.Println(name) // outsideThe inner name stops being accessible at the closing brace. Replacing its := with = would instead update the outer string. The difference is scope, not a special rule about if.
Use the rule while reviewing real code
In a multi-name short declaration, at least one non-blank name must be new in the same block. Existing names in that block keep their declared types. Before changing := to =, find every declaration and branch exit; an inner err may be a deliberate short-lived error, or it may hide the value returned later.
TAKE THIS WITH YOU
Read the block before the operator. Prefer a short temporary scope when it clarifies ownership; use assignment when an existing result must change.
Check your understanding
Which statement is correct about nested :=?
Go to the source
Progress stays in this browser. No account needed.