:= — short variable declaration: creates a new variable and assigns a value in one step. = — assignment: updates the value of an already-declared variable.
Short declarations are the standard way to introduce variables inside functions. The type is inferred from the right-hand side. At least one variable on the left must be new.
1func process() {2 x := 42 // declares x3 y, z := 1, 2 // declares y and z4 x, w := 3, 4 // OK: x reassigned, w is new5}
Assignment updates existing variables. Use it after declaration for reassignment, swapping, or receiving values.
1var count int2for i := 0; i < 10; i++ {3 count++ // assignment4}56var a, b int7a, b = b, a // swap
When to use:
if/for init.Common mistakes:
:= in nested blocks hides outer variables.:= when all variables exist — error.:= at package level — not allowed.for loops: new variable per iteration.