:= — short variable declaration: creates a new variable and assigns a value. = — assignment: sets the value of an existing variable.
Short declarations are the idiomatic way to introduce variables in Go functions. The type is inferred from the right-hand side, making the code concise and readable.
1func main() {2 x := 42 // declares x as int3 y, z := 1, "a" // declares y as int, z as string4 x = 100 // assignment — x already exists5}
Assignment (=) updates existing variables. It's used for reassignment, swapping, and receiving values from channels or functions.
1var count int2for i := 0; i < 10; i++ {3 count++ // assignment4}56a, b := 1, 2 // short declaration7a, b = b, a // swap via assignment
When to use:
if/for init.Common mistakes:
:= in nested blocks.:= when all variables are already declared — error.:= at package level — not allowed; use var.for loops: new variable per iteration instead of accumulating.