:= — short variable declaration: declares a new variable AND assigns a value. = — simple assignment: assigns a value to an already-declared variable.
The short declaration operator creates the variable in the current block scope. The type is inferred from the right-hand side. At least one variable on the left must be new.
1func main() {2 x := 42 // declares x as int3 y, z := 1, 2 // declares y and z4 x, w := 3, 4 // OK: x reassigned, w is new5}
Assignment (=) requires the variable to already exist in scope. You can assign to multiple variables on the left if all are pre-declared.
1var x int2x = 10 // assignment — OK34var a, b int5a, b = 5, 6 // multi-assignment — OK67c = 7 // error: undeclared c
When to use:
if/for init and multiple return values.Common mistakes:
x := 1 inside an if block creates a new x.:= in a for loop with an existing variable — creates a new scoped variable.:= outside a function body — not allowed at package level.