Short declaration
:= declares one or more variables and assigns them in a single statement, inferring each type from the right-hand side. It is legal only inside functions.
Detailed Explanation
Most Go you read inside functions uses := rather than var. port, err := strconv.Atoi(raw) declares port as int and err as error, then assigns both. You do not repeat the types. The statement exists to keep the happy path short when the types are obvious from the call.
At least one name must be new. := can mix new names and old ones in the same block. n, err := f() after var err error reuses err and declares n. err := f() when err already exists in that block is a compile error: nothing new was declared. This reuse rule is why err can flow down a function without a new err on every line.
Types come from the right-hand side. n := 0 is int. n := int32(0) is int32. s := nil does not compile: nil has no default type. Write var s []byte or s := []byte(nil). Untyped constants pick a default (int, float64, complex128, bool, string, rune).
Scope is the enclosing block, not the function. if v, err := f(); err != nil declares v and err for the if/else only. After the closing brace they are gone. A later := with the same names is a new declaration, not an assignment to the inner ones. That is useful for keeping err local, and a trap when you meant to keep v.
Redeclaration is not the same as shadowing. Redeclaration happens in one := in one block, reusing an existing name. Shadowing happens when an inner block introduces the same name again. if err := g(); err != nil next to an outer err shadows: the outer err stays as it was. go vet with a shadow analyzer flags the inner :=.
What it costs. Nothing at runtime — := is syntax. The cost is in misread types and accidental shadows. When the inferred type is surprising, write var n int64 = 0 or n := int64(0) so the next reader does not have to reconstruct the default.
Code Examples
package main
import (
"fmt"
"strconv"
)
func main() {
port, err := strconv.Atoi("8080")
if err != nil {
fmt.Println(err)
return
}
fmt.Println(port)
}func reuseErr(raw string) (int, error) {
var err error
n, err := strconv.Atoi(raw) // declares n, reuses err
if err != nil {
return 0, err
}
return n, nil
}func scope() {
if v, err := strconv.Atoi("9"); err == nil {
fmt.Println(v)
}
// v and err are not in scope here
}Common Gotchas
All left-hand names must be identifiers
you cannot write `m[k] := v`. Use `=` for map and slice elements.