:= — 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 inside functions. The type is inferred from the right side. If all variables on the left already exist, the compiler errors.
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. 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.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.:= when all variables are already declared — compiler error.