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