Variables and short declarations
Use `var` and `:=` with the exact redeclaration and initialization rules in mind; short declarations do not mean loose scoping.
Canonical guidance
vardeclares variables explicitly and can omit an initializer:=both declares and initializes, but only when at least one name is new in the current block- scope and block boundaries decide whether code redeclares or shadows
Use when
- debugging
no new variables on left side of := - deciding whether a declaration is new or reused
- reviewing initialization style
Avoid
- assuming
:=always creates a new variable - mixing new and old names casually in long assignment lists
- using short declarations where the resulting scope becomes hard to read
Preferred pattern
f, err := os.Open(name)
if err != nil {
return err
}
defer f.Close()
Anti-pattern
- writing
x, err := f()later in the same block when neither name is actually new
Explanation: This is tempting during refactors, but same-block short declarations have a strict rule and fail when no new non-blank identifier is introduced.
Why
- many common compile failures in Go are direct consequences of the short declaration rule