:= — short variable declaration: introduces a new variable and assigns its value. = — assignment: updates an already-declared variable.
Short declarations are the standard way to declare variables in Go functions. The type is inferred from the right-hand side. You need at least one new variable on the left — otherwise the compiler rejects it.
1func example() {2 name := "Alice" // new: name3 age := 30 // new: age4 name, role := "Bob", "admin" // OK: role is new5 name = "Charlie" // assignment — name exists6}
Simple assignment requires the variable to already exist in the current scope. Use it to update values, swap variables, or reassign after checks.
1var x int2x = 42 // assignment34var a, b int5a, b = b, a // swap67result, err := doWork()8if err != nil {9 err = fmt.Errorf("wrapping: %w", err) // reassignment10}
When to use:
if/for init.Common mistakes:
:= inside a nested block creates a new variable that hides the outer one.:= with all existing variables on the left — compiler error.:= at package level — not allowed; use var.for loops: x := creates a new variable each iteration.