:= — short variable declaration: creates a new variable and assigns a value in one step. = — assignment: sets the value of an existing variable.
Short declarations are the idiomatic way to introduce variables inside functions. The type is inferred from the right side. If you use := and all variables on the left already exist, the compiler errors — you need at least one new variable.
1func process() {2 name := "Alice" // declares name3 age := 30 // declares 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. It's used after initial declaration to update values, swap variables, or receive multiple return values.
1var x int2x = 42 // assignment34var a, b int5a, b = b, a // swap — both already declared67result, err := doWork()8if err != nil {9 err = fmt.Errorf("wrapping: %w", err) // reassignment10}
When to use:
if/for init statements.Common mistakes:
:= inside an if block creates a new variable that hides the outer one.:= at package level — only var is allowed there.:= in a loop creates a new variable each iteration — use = if you want to accumulate.