:= — short variable declaration: declares one or more new variables and assigns values. = — assignment: updates the value of an already-declared variable.
Short declarations are confined to function bodies. They infer types automatically and require at least one new variable on the left side. This makes them concise and idiomatic for most Go code.
1func fetchData() {2 url := "https://api.example.com" // new: url3 resp, err := http.Get(url) // new: resp, err4 defer resp.Body.Close()5 body, _ := io.ReadAll(resp.Body) // new: body6 fmt.Println(string(body))7}
Assignment (=) updates existing variables. It's used after the initial declaration for reassignment, swapping, or updating state.
1var count int2for i := 0; i < 10; i++ {3 count++ // assignment to existing variable4}56x, y := 1, 2 // short declaration7x, y = y, x // swap using assignment
When to use:
if/for init statements.Common mistakes:
:= inside an if block creates a new variable that hides the outer one.:= with all existing variables on the left — compiler error (need at least one new).:= at package level — not allowed; use var instead.for loops: x := creates a new variable each iteration instead of reusing.