Variables
Go variables come in three flavours: var (explicit), := (short declaration with inference), and const. Zero values are guaranteed: 0 for ints, \"\" for strings, nil for pointers, slices, maps, channels.
The three flavours
EXAMPLE
package main
import "fmt"
// Package-level — must use var, not :=
var (
appName = "hello"
version = 3
)
const MaxUsers = 1000 // compile-time constant
func main() {
// Short declaration — only inside functions, types inferred
name := "Ada"
age := 36
// Multiple at once
a, b := 1, 2
a, b = b, a // swap, no temp var
// Explicit type
var pi float64 = 3.14
// Zero values — declared but not initialised
var (
count int // 0
ok bool // false
items []int // nil
cache map[string]int // nil — cannot insert into a nil map
)
items = append(items, 1) // append works on nil slices
cache = make(map[string]int) // must make before use
fmt.Println(name, age, pi, a, b, count, ok, items, cache)
}
Why it matters
Unused variables are a compile error. The discipline forces tidy code — you can’t leave dead bindings lying around.
Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.
Example
Exercise
Short variable declaration.
name
"Ada"
Two characters.
Discussion
Loading…