Declaring variables — var, :=, and constants with iota
Go gives you two different ways to declare a variable, and they're not interchangeable stylistic choices — one only works in certain places, and knowing which is which is one of the first things that trips up someone new to the language.
Beginner
2 min read
Two ways to declare a variable, not one
var age int = 25 // explicit form: keyword, name, type, valuevar name = "Ada" // type inferred from the valueage := 25 // shorthand: type AND var keyword both inferred
var is the general-purpose form and works everywhere — inside a function,
at package level, with or without an initial value. The short variable
declaration (:=) is shorthand available only inside a function body —
using := at package level is a compile error, which is the single most
common thing that trips someone up moving from var to := for the first
time.
Why := exists at all, given var already works
:= isn't a different feature so much as a shorter way to write the
extremely common case of "declare a variable and immediately give it a
value, letting Go infer the type" — which is most of what local variable
declarations actually look like in real code. var stays necessary for
package-level declarations, and for the less common case of declaring a
variable with no initial value (getting its zero value instead, as
covered in the types lesson).
Constants, and the iota shortcut for sequences
const declares a value that can never change after compilation — unlike
var, a constant's value must be knowable at compile time, not computed at
runtime:
const Pi = 3.14159const MaxRetries = 3
For a sequence of related constants, Go has a specific shorthand: iota,
which starts at 0 inside a const block and increments by one for each
subsequent line:
This looks unusual coming from languages with explicit enums, but it's
solving the same problem: naming a small, fixed set of related integer
values without manually writing out 0, 1, 2, 3 and risking a typo if the
list ever gets reordered.
Why this matters day to day
Seeing := fail to compile at package level, or seeing iota in someone
else's Go code for the first time, are both extremely common early moments
— recognizing both immediately as intentional, idiomatic Go (not a bug or
unusual code) is exactly the kind of small friction this lesson exists to
remove before it costs real debugging time.