var, const, the := short form, zero values, and iota.
Constants and iota
A constant is a name for a value that can never change. Constants are checked at compile time, never take up memory at runtime, and can be used in contexts where a regular variable can't (like array sizes).
Basic constants
const Pi = 3.14159
const Greeting = "hello"
const MaxUsers = 1_000_000 // _ is just a separator
A typed constant has the type baked in. An untyped constant (no type written) is flexible — it adopts whatever type fits the spot:
const a = 1 // untyped int constant
const b int32 = 1 // typed int32 constant
var x int64 = a // ok — a takes int64
var y int64 = b // compile error — b is int32, not int64
iota — auto-incrementing constants
iota is a counter that starts at 0 inside a const ( ... ) block and increments
by 1 for each line. It's how Go does enums.
go playground
Loading...
Bit flags with iota
A common pattern: shift iota to get powers of two.
go playground
Loading...
Skipping values with _
If you don't want every value, blank-out the ones you skip:
const (
_ = iota // skip 0
KB = 1 << (10 * iota) // 1 << 10
MB // 1 << 20
GB // 1 << 30
)
What constants can and can't be
Constants must be values the compiler can evaluate at compile time:
- ✅ Numbers, strings, booleans, characters.
- ✅ Expressions over other constants (
const Two = 1 + 1). - ❌ Function calls (
const Now = time.Now()— runtime!). - ❌ Slices, maps, structs (use
varinstead).
Given the Weekday block above (Sunday = iota, then Monday, Tuesday, Wednesday, …), what value does Wednesday hold?