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

  1. 01

    Declare

    go
    size := 8

    Creates a name in this block

  2. 02

    Reuse

    go
    size = 12

    Assigns the existing name

  3. 03

    Mixed declaration

    go
    size, 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.

Official reference ↗

Work through the exercise

go
value, err := parse(input)
if err != nil {
	return err
}
Try it yourself

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.