:= — short variable declaration: declares one or more new variables and assigns values. = — assignment: sets the value of already-declared variables.
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:
:= in a nested block creates a new variable that hides the outer one.:= with all existing variables — compiler error (need at least one new).:= at package level — not allowed; use var.:= in a for range creates a new loop variable each iteration.