Variables in Go
Variables store values with optional explicit types and safe zero values. Prefer small, explicit scopes and initialize near first use.
Declaration
Variables can be declared with explicit types or with type inference. Use explicit types when the zero value is meaningful or to document intent.
var x int // zero value 0
var s string = "go" // with initializer
var a, b = 1, 2 // type inferred
Short declaration
Short declarations are limited to function bodies. They infer types from right-hand expressions.
n := 42 // inside functions only
x, y := 1, 2 // redeclare at least one new name on the left side
Notes:
:=both declares and initializes; at least one variable on the left must be new- Use
varat package scope, or when you need the zero value without initialization
Multiple assignment and swap
Multiple assignment is evaluated right-to-left, enabling swaps without temporaries.
x, y = y, x
u, v, w := 1, 2, 3
u, v, w = v, w, u
Scope
- Package-level vars are accessible within the package
- Function-level vars shadow outer names
- Use short, limited scopes; keep variables near first use
package pkg
var pkgVar = 1 // package scope
func f() {
x := 2 // function scope
if true {
x := 3 // shadows outer x
_ = x
}
_ = x; _ = pkgVar
}
Zero values
Zero values prevent uninitialized-memory bugs and let you rely on defaults.
var (
zi int // 0
zs string // ""
zb bool // false
zm map[int]int // nil
)
Constants vs variables
- Constants are immutable, compile-time values
- Variables are mutable, runtime values
Best practices
- Prefer short
:=locally; usevarfor zero value or documentation - Keep scopes narrow; avoid shadowing unintentionally
- Initialize reference types (
map,slice,chan) before writing - Name variables descriptively; avoid 1-2 character names except for tiny scopes
Summary
- Use explicit types when clarity matters; rely on inference for brevity
- Favor small scopes and clear initialization