Go core · 3 MIN READ
:= declares, = assigns
Choose between := and = without guessing, and know when := is illegal.
:= declares and assigns in one step inside a function. At least one non-blank name on the left must be new in the current block; otherwise the compiler reports "no new variables".
A short declaration may mix new names with names already declared in that same block. Inside a nested block, however, it may introduce a different variable with the same spelling. Use = when the intention is to update an existing variable.
SEE THE IDEA
Creation and reassignment are different steps
- 01
Declare
gosize := 8Creates a name in this block
- 02
Reuse
gosize = 12Assigns the existing name
- 03
Mixed declaration
gosize, err := read()At least one name must be new
Short declarations are for local variables; package-level declarations use var.
In practice
Read a short declaration together with its block. Inside a nested if or for block, the same spelling may introduce a different variable. A short declaration with multiple names may reuse names from that same block when at least one other name is new.
Watch out
An inner err := can shadow an outer err. Use = when you intend to update an existing variable.
Work through the exercise
value, err := parse(input)
if err != nil {
return err
}Trace each value and write down your reasoning. Copy the source into GopherForge or your local Go environment to compile and check it. This web page does not execute your code or send it to a compiler service.
Progress stays in this browser. No account needed.