These are the notes for Go episode 5. You will learn why bare "magic numbers" break programs, how const gives a number a name that can never change, what can and can't be a constant, constant expressions, the difference between typed and untyped constants (and their default types), why constants can be far bigger than any variable, and iota, Go's little counting machine, which gives you enums, skipped values, size units like KB/MB/GB, and bit flags. Every example runs as-is in the SyntaxPilot compiler (language: Go); outputs and errors are from real runs (Go 1.24).
The problem: what does status 2 mean?
A food-delivery app. Every order has a status, stored as a number. The kitchen team decided that 2 means "out for delivery". The customer app team decided that 2 means "delivered". So while the rider is still on the road, the customer's phone says: delivered.
package main
import "fmt"
func main() {
status := 2
// kitchen screen: 2 means "out for delivery"
fmt.Println("Kitchen, out for delivery:", status == 2)
// customer screen: someone used 2 for "delivered"
fmt.Println("Customer, delivered:", status == 2)
}
Kitchen, out for delivery: true
Customer, delivered: true
==(double equals) asks a question: "are these equal?" It gives abool,trueorfalse. (One=puts a value in; two==compare.)//starts a comment: a note for humans that Go ignores.
Both true. The order is out for delivery and delivered at the same time. A bare number like this 2, with no name explaining it, is called a magic number.
Why did it fail? A number doesn't say what it means. So let's give it a name.
The obvious fix: a variable (and why it fails)
A package-level variable (declared outside every function, so every function can see it; episode 3) called Delivered, equal to 3. Now the check reads status == Delivered. But somewhere, someone wrote a "quick fix":
package main
import "fmt"
var Delivered = 3
func main() {
Delivered = 2 // a "quick fix" somewhere
status := 2
fmt.Println("Customer, delivered:", status == Delivered)
}
Customer, delivered: true
true again. A variable can be changed by anyone, anywhere, and Go won't say a word. We need a name whose value can never change.
The fix: const, a value carved in stone
| In real life | In Go |
|---|---|
| A whiteboard: anyone can rub it out | var: can change at any time |
| A stone foundation plaque: carved once, forever | const: fixed when the program is built |
A constant is a named value that can never change. You make one with the keyword const instead of var. Same program, with the quick fix still there:
package main
import "fmt"
const Delivered = 3
func main() {
Delivered = 2
fmt.Println(Delivered)
}
./main.go:8:5: cannot assign to Delivered (neither addressable nor a map index expression)
In plain words: Delivered is not a box in memory you can write into (it is not addressable, meaning it has no memory address you could store into). It's a fixed value. (A map index expression is a way of writing into a map, a collection type you'll meet later; it doesn't apply here.) The bug can't even be written.
Good to know: unlike an unused variable, an unused constant is not an error. A program with const tax = 18 that never uses tax compiles and runs.
The catch: a constant must be known while compiling
Compiling is the step where Go checks your program and turns it into something the computer can run, before it starts. A constant's value must be known at that moment. What about the current time, as a constant?
package main
import (
"fmt"
"time"
)
const start = time.Now()
func main() {
fmt.Println(start)
}
./main.go:8:15: time.Now() (value of struct type time.Time) is not constant
time.Now() (from the time package) gives the current time. It's only known when the program runs (at run time), so it can't be carved in advance. (A struct type is a type that groups several values together; time.Time is one. Structs come later in the course.) Use a variable instead: start := time.Now().
Constant expressions, typed and untyped constants
const secondsPerDay = 24 * 60 * 60 // a constant expression
const limit = 10 // untyped
const limit int = 10 // typed
- A constant can be a calculation, as long as every part is itself constant.
24 * 60 * 60is worked out once, while compiling. This is called a constant expression. (*means multiply.) - Untyped constant: declared without a type, like
const limit = 10. It is just the idea of the number ten. It fits into any numeric type it's used with, as long as the value fits. - Typed constant: declared with a type, like
const limit int = 10. It is a realint, with all of episode 4's strict rules (no mixing types).
package main
import "fmt"
const secondsPerDay = 24 * 60 * 60
const limit = 10
func main() {
var cups int = limit
var litres float64 = limit
fmt.Println(secondsPerDay, cups, litres*1.5)
fmt.Printf("%T\n", limit)
}
86400 10 15
int
- 86400 seconds in a day.
- The untyped
10went happily into anintand into afloat64: 10 × 1.5 is 15. - When nothing decides its type (here,
Printfaccepts any type),limitbecomes anint. That's its default type. (%Tprints a value's type.)
Now a typed limit, multiplied by a float64:
package main
import "fmt"
const limit int = 10
func main() {
var litres float64 = 2.5
fmt.Println(litres * limit)
}
./main.go:9:17: invalid operation: litres * limit (mismatched types float64 and int)
The same error as episode 4. Typed constants are strict. Leave constants untyped unless you have a reason.
Default types
What default type does each kind of untyped constant get?
package main
import "fmt"
const pi = 3.14159
const letter = 'A'
const name = "Go"
func main() {
fmt.Printf("%T %T %T\n", pi, letter, name)
}
float64 int32 string
| Untyped constant | Default type |
|---|---|
whole number, 10 |
int |
decimal, 3.14159 |
float64 |
single character in single quotes, 'A' |
int32, i.e. rune (the character's Unicode number, episode 4) |
text in double quotes, "Go" |
string |
Huge, precise constants: they don't overflow (until you use them)
const huge = 1 << 100
<<is the left shift: it moves a number's bits (its binary on/off switches, episode 4) to the left. Each step left doubles the number.1 << 3is 1 → 2 → 4 → 8. So1 << 100is 2 to the power 100.- That's a 31-digit number, far beyond
int64's 9.2 quintillion. As a constant, it's allowed. - Constant maths in Go is exact, with very high precision (arbitrary precision): the language rules say at least 256 bits. It only needs to fit when it finally lands in a variable or a function call.
>>is the right shift: it moves bits right, and each step halves the number.
package main
import "fmt"
const huge = 1 << 100
func main() {
fmt.Println(huge >> 98)
}
4
Shifting right by 98 divides by 2⁹⁸, leaving 2² = 4. The giant number was handled exactly, and the result fits in an int. Now print huge itself:
package main
import "fmt"
const huge = 1 << 100
func main() {
fmt.Println(huge >> 98)
fmt.Println(huge)
}
./main.go:9:17: cannot use huge (untyped int constant 1267650600228229401496703205376) as int value in argument to fmt.Println (overflows)
There's the full 31-digit number. When it lands in Println, it becomes an int (its default type), and it doesn't fit: it overflows. (An argument is a value you pass into a function call.)
The next problem: numbering by hand
Now our statuses are constants, each number typed by hand. Then the business adds a new status, Packed, between Preparing and OnTheWay. Every number after it has to be retyped by hand. That's exactly the kind of job a computer should do.
A const block groups several constants inside const ( ... ) round brackets:
package main
import "fmt"
const (
Placed = 0
Preparing = 1
Packed = 2
OnTheWay = 3
Delivered = 4
)
func main() {
fmt.Println(Placed, Preparing, Packed, OnTheWay, Delivered)
}
0 1 2 3 4
It works today, but every insertion means retyping numbers, and one missed number brings back the status-2 bug.
The fix: iota, the token machine
| At a bank | In Go |
|---|---|
| A token machine: press, get 0, 1, 2, 3 ... | iota: 0 on the first line of a const block, +1 on each line |
| Reset each morning, back to 0 | a new const block: iota starts again at 0 |
At a bank's token machine, each person who presses it gets the next number. Nobody numbers anything by hand. Go has exactly that, called iota. Inside a const block, iota is 0 on the first line and goes up by one on every line. And like the machine reset each morning, every new const block starts iota at 0 again.
The enum pattern
type Status int
const (
Placed Status = iota // 0
Preparing // 1
Packed // 2
OnTheWay // 3
Delivered // 4
)
type Status intis a type definition: it creates a brand-new type calledStatus, built onint(its underlying type). Episode 19 covers type definitions properly.Placed Status = iota: Placed is of typeStatusand equalsiota, which is 0.- The next lines say nothing at all. In a const block, a line with only a name repeats the previous line's type and expression, and
iotahas gone up. So Preparing is 1, Packed is 2, and so on. - A fixed list of named values like this is called an enum, short for enumeration. Go has no
enumkeyword: this is the Go way.
package main
import "fmt"
type Status int
const (
Placed Status = iota
Preparing
Packed
OnTheWay
Delivered
)
func main() {
fmt.Println(Placed, Preparing, Packed, OnTheWay, Delivered)
fmt.Printf("%T\n", Delivered)
}
0 1 2 3 4
main.Status
0 to 4, numbered for us. Add a new status anywhere and everything renumbers itself. The type is main.Status: Status from our main package.
The type gives extra safety
Compare a Status with a plain int:
package main
import "fmt"
type Status int
const (
Placed Status = iota
Preparing
OnTheWay
Delivered
)
func main() {
var s Status = OnTheWay
var n int = 2
fmt.Println(s == n)
}
./main.go:17:22: invalid operation: s == n (mismatched types Status and int)
A random int can't be mistaken for a status. Comparing with a named constant, like s == OnTheWay, works fine.
More iota tricks: skipping values and expressions
_ = iota // skip 0
KB = 1 << (10 * (iota + 1)) // the expression repeats: KB, MB, GB
- Skipping values: sometimes you don't want to start at 0, because 0 is what an unset variable holds (its zero value, episode 3). Put
_, the blank identifier (the dustbin from episode 3), on the first line, and the 0 is thrown away. The first real name gets 1. - iota in expressions:
iotacan sit inside any constant expression.1 << 10is 1024, a kilobyte (KB). Each next line repeats the expression withiotaone higher: 2²⁰ is a megabyte (MB), 2³⁰ a gigabyte (GB). (Here each unit is 1024 times the previous one.)
package main
import "fmt"
const (
_ = iota
Small
Medium
Large
)
const (
KB = 1 << (10 * (iota + 1))
MB
GB
)
func main() {
fmt.Println(Small, Medium, Large)
fmt.Println(KB, MB, GB)
}
1 2 3
1024 1048576 1073741824
1, 2, 3. And 1024, about a million, and about a billion. Notice iota started again at 0 in the second block: that's why the expression says iota + 1 (so the first line uses 10 × 1).
Bit flags: pizza toppings as switches
| A pizza order | In Go |
|---|---|
| Four topping switches: cheese, olives, onion, paneer | bit flags: one bit per option, 1, 2, 4, 8 |
| Cheese and onion: two switches on | a | b, bitwise OR: turn on both bits → 0101 |
| Is onion on? Look at one switch | x & Onion, bitwise AND: keep only that bit |
A pizza can have any mix of four toppings. Remember, bits are switches, so give each topping its own bit: 1, 2, 4 and 8. These are called bit flags.
- Bitwise OR,
|(the bar symbol): a bit is on in the result if it's on in either side. Use it to combine flags. - Bitwise AND,
&(the ampersand): keeps only the bits that are on in both sides. If anything is left (not 0), that flag is on. Episode 6 (operators) goes deeper.
package main
import "fmt"
const (
Cheese = 1 << iota
Olives
Onion
Paneer
)
func main() {
fmt.Println(Cheese, Olives, Onion, Paneer)
order := Cheese | Onion
fmt.Printf("%04b = %d\n", order, order)
fmt.Println("onion?", order&Onion != 0)
fmt.Println("paneer?", order&Paneer != 0)
}
1 2 4 8
0101 = 5
onion? true
paneer? false
Cheese = 1 << iota: each next line shifts one more, giving 1, 2, 4, 8.%bis the Printf verb that prints a number in binary.%04bpads it to 4 digits with leading zeros.!=means "is not equal to".order&Onion != 0asks "is the onion bit on?".- The order is
0101in binary, which is 5. Four yes-or-no answers packed into one small number.
Common mistakes (and the real error messages)
| You wrote | Real error | Fix |
|---|---|---|
Delivered = 2 (a const) |
cannot assign to Delivered (neither addressable nor a map index expression) |
use var if it must change |
limit++ (a const) |
cannot assign to limit (neither addressable nor a map index expression) |
a constant can never change |
const start = time.Now() |
time.Now() (value of struct type time.Time) is not constant |
start := time.Now() |
const limit int = 10, then litres * limit |
invalid operation: litres * limit (mismatched types float64 and int) |
const limit = 10 (untyped) |
fmt.Println(huge) with huge = 1 << 100 |
cannot use huge (untyped int constant 1267650600228229401496703205376) as int value in argument to fmt.Println (overflows) |
shift it down, or use math/big |
s == n (Status vs int) |
invalid operation: s == n (mismatched types Status and int) |
compare with a named constant: s == OnTheWay |
status == 2 everywhere |
no error: a magic number means different things in different places | name it with const |
| numbering an enum by hand | no error, until someone inserts a value and misses a renumber | use iota |
Mini project: how big is that movie?
First the size constants, with the zero skipped, so KB is 1 << 10. A movie file of three and a half billion bytes. Print the bytes, then convert to float64 and divide by GB, and by MB.
package main
import "fmt"
const (
_ = iota
KB = 1 << (10 * iota)
MB
GB
)
func main() {
// Mini project: how big is that movie?
movie := 3500000000
fmt.Println("bytes:", movie)
fmt.Printf("GB: %.2f\n", float64(movie)/GB)
fmt.Printf("MB: %.0f\n", float64(movie)/MB)
}
bytes: 3500000000
GB: 3.26
MB: 3338
- This time the skipped line uses up
iota0, soKBgetsiota1:1 << 10. No+ 1needed. %.2fprints a float with 2 decimals,%.0fwith none (rounded).- The untyped constant
GBhappily divided afloat64. Untyped constants fit anywhere.
Extension: how many movies fit on a 128 GB phone?
package main
import "fmt"
const (
_ = iota
KB = 1 << (10 * iota)
MB
GB
)
func main() {
// Extension: how many movies fit on a 128 GB phone?
movie := 3500000000
phone := 128 * GB
fmt.Println("phone bytes:", phone)
fmt.Println("movies that fit:", phone/movie)
}
phone bytes: 137438953472
movies that fit: 39
128 * GB is a constant expression that becomes an int. Dividing two ints gives a whole number (episode 4): 39 whole movies.
Practice
- Make an enum for the days of the week with a
Weekdaytype andiota. - Make a traffic-light enum (Red, Yellow, Green) that starts at 1, using
_. - Add
TB(terabyte) to the KB, MB, GB block. - Make three permission flags (Read, Write, Exec), combine two, and check all three.
Solutions and hints
- Days of the week:
package main
import "fmt"
type Weekday int
const (
Sunday Weekday = iota
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
)
func main() {
fmt.Println(Sunday, Wednesday, Saturday)
fmt.Printf("%T\n", Friday)
}
0 3 6
main.Weekday
- Skipping 0 means an unset light is not mistaken for Red:
package main
import "fmt"
type Light int
const (
_ Light = iota
Red
Yellow
Green
)
func main() {
var unset Light
fmt.Println(Red, Yellow, Green)
fmt.Println("unset light:", unset, "is red?", unset == Red)
}
1 2 3
unset light: 0 is red? false
- Just add one more line; the expression repeats:
package main
import "fmt"
const (
KB = 1 << (10 * (iota + 1))
MB
GB
TB
)
func main() {
fmt.Println(KB, MB, GB, TB)
}
1024 1048576 1073741824 1099511627776
- Permission flags with
1 << iota:
package main
import "fmt"
const (
Read = 1 << iota
Write
Exec
)
func main() {
perm := Read | Write
fmt.Printf("%03b = %d\n", perm, perm)
fmt.Println("can read?", perm&Read != 0)
fmt.Println("can write?", perm&Write != 0)
fmt.Println("can exec?", perm&Exec != 0)
}
011 = 3
can read? true
can write? true
can exec? false
Quick quiz
What does this print (with the fmt.Println inside main)?
const (
x = iota * 10
y
_
z
)
fmt.Println(x, y, z)
- A.
0 10 20 - B.
0 10 30 - C.
0 1 3 - D. Compile error
Answer
B. 0 10 30. iota is 0, 1, 2, 3 on the four lines, and each empty line repeats iota * 10. The _ line takes 20 and throws it away, but it still uses up iota 2, so z gets 3 × 10 = 30.
Interview questions
- What is the difference between
constandvarin Go? Why can't you assign to a constant? - Why can't
time.Now()be a constant? - What is the difference between a typed and an untyped constant? Which should you prefer?
- What are the default types of the untyped constants
10,3.14,'A'and"Go"? - Why does
const huge = 1 << 100compile, butfmt.Println(huge)fail? - What is
iota? What value does it have on each line, and when does it reset? - How do you write an enum in Go, given there is no
enumkeyword? - How do you skip the zero value in an iota enum, and why would you?
- How do bit flags work? How do you combine and test them?
Glossary
| Term | Meaning | Example |
|---|---|---|
| Magic number | a bare number in code with no name saying what it means | status == 2 |
| Comment | a note for humans that Go ignores, starting with // |
// kitchen screen |
| == | asks "are these equal?" and gives a bool | status == 2 |
| != | asks "are these not equal?" | order&Onion != 0 |
| Package-level variable | a variable declared outside all functions, visible to every function | var Delivered = 3 |
| const | the keyword that declares a constant | const Delivered = 3 |
| Constant | a named value fixed while compiling that can never change | Delivered |
| Addressable | has a place in memory you can write into; constants are not | variables are addressable |
| Compile time | while Go checks and builds the program, before it runs | constant maths happens here |
| Run time | while the program is running | time.Now() is known here |
| time.Now() | gives the current date and time | start := time.Now() |
| Struct type | a type that groups several values together (covered later) | time.Time |
| Constant expression | a calculation made only of constants, worked out while compiling | 24 * 60 * 60 |
| Untyped constant | a constant with no fixed type yet; fits any numeric type if the value fits | const limit = 10 |
| Typed constant | a constant with a declared type; follows strict type rules | const limit int = 10 |
| Default type | the type an untyped constant becomes when nothing else decides | 10 → int, 3.14 → float64, 'A' → int32, "Go" → string |
| rune | another name for int32; one character's Unicode number |
'A' = 65 |
| Arbitrary precision | constants are computed exactly with huge precision (at least 256 bits) | 1 << 100 |
| Overflows | the error when a constant is too big for the type it lands in | fmt.Println(huge) |
| Argument | a value passed into a function call | huge in Println(huge) |
| Shift left << | moves bits left; each step doubles | 1 << 3 = 8 |
| Shift right >> | moves bits right; each step halves | huge >> 98 |
| Const block | several constants grouped in const ( ... ) |
const ( Placed = 0 ... ) |
| iota | inside a const block: 0 on the first line, +1 each line; resets in each block | Placed Status = iota |
| Implicit repetition | a const line with only a name repeats the previous line's type and expression | Preparing |
| Type definition | creates a new named type built on an existing one | type Status int |
| Underlying type | the type a defined type is built on | int for Status |
| main.Status | how %T shows a type defined in package main |
Printf("%T", Delivered) |
| Enum (enumeration) | a fixed list of named values; in Go, a typed const block with iota | Placed ... Delivered |
| Enum pattern | type X int + const ( A X = iota; B; C ) |
statuses |
| Blank identifier _ | throws a value away; in a const block, skips an iota value | _ = iota |
| Zero value | the value an unset variable holds (0 for numbers) | var l Light is 0 |
| Skipping values | using _ so the first real name doesn't get 0 |
Small = 1 |
| KB / MB / GB / TB | kilobyte 2¹⁰, megabyte 2²⁰, gigabyte 2³⁰, terabyte 2⁴⁰ bytes (here) | KB = 1024 |
| Bit | one binary on/off switch, 0 or 1 | |
| Binary | numbers written with only 0 and 1 | 0101 = 5 |
| Bit flags | one bit per yes/no option, so many options fit in one number | Cheese = 1 << iota |
| Bitwise OR | | a bit is on if it's on in either side; combines flags | Cheese | Onion = 5 |
| Bitwise AND & | a bit is on only if on in both sides; tests a flag | order & Onion |
| %b / %04b | Printf verb: print in binary / binary padded to 4 digits | %04b of 5 → 0101 |
| %T / %d / %.2f / %.0f | Printf verbs: type, integer, float with 2 / 0 decimals | %.2f → 3.26 |
| math/big | a standard package for numbers bigger than int64 (later) |
Summary
- A magic number hides its meaning; a variable gives it a name but can still be changed by anyone.
constvalues can never change (cannot assign to ...), and must be known while compiling (time.Now()is not constant).- Constant expressions like
24 * 60 * 60are worked out once, while compiling. - Untyped constants fit any numeric type; typed ones follow strict rules. Default types:
int,float64,int32(rune),string. - Constant maths is exact (
1 << 100is fine); the result must fit where it lands. iotacounts 0, 1, 2 in a const block and restarts in each new block. Enums withtype Status int; skip 0 with_; build KB, MB, GB from one expression; bit flags with1 << iota, combined with|, checked with&.
Next episode: operators and expressions. A program that checks whether a number is odd gets it wrong for minus three. To find out why, you'll meet every operator Go has.