Day 002 — Variables, Constants & iota¶
Month 1 · Week 1 · ⬅ Day 001 · Day 003 ➡ · Journal index
🎯 Learning Objective¶
Declare variables and constants every idiomatic way, and use iota to build enums and bit flags.
📚 Topics¶
var,:=,const, block declarations- Zero values · typed vs untyped constants ·
iota
📖 Reading / Sources¶
- Learning Go ch.2
- Tour of Go — Variables & Constants
- Effective Go — Constants
📝 Notes¶
- Three declaration forms:
var x int = 5(explicit),var x = 5(inferred),x := 5(short — functions only). - Zero values mean you never have "uninitialized" variables:
0,0.0,false,"",nil(pointers/slices/maps/channels/interfaces/funcs). Design so the zero value is useful → [[zero-values]]. - Constants are compile-time; they can be untyped, which lets one constant adapt to many numeric contexts (
const x = 5works as int or float64 depending on use). iotaresets to 0 in eachconstblock and increments by 1 per line — the idiomatic enum builder. Combine with1 << iotafor bit flags.- Unused local variables are a compile error (not a warning). Same for unused imports.
💻 Code Examples¶
Full code:
examples/vars/main.go· Run:go run ./examples/vars
🏋️ Exercises / Practice¶
| Exercise | Status | Link |
|---|---|---|
Reimplement Weekday enum with iota |
✅ | examples/vars |
Bit-flag permissions with 1 << iota |
✅ | examples/vars |
🐛 Mistakes Made¶
- Tried
:=at package level → onlyvar/constwork outside functions. - Declared a variable I didn't use →
declared and not used. Removed it.
❓ Open Questions¶
- When should a constant be typed vs untyped? (Rule of thumb: leave untyped unless you need to restrict it.)
🧠 Active Recall (answer without looking)¶
- Q: What does
iotaequal on the 3rd line of aconstblock?A
2 — it starts at 0 and increments by one per ConstSpec line in the block. - Q: Why does Go reject an unused local variable?
A
It's a deliberate language rule to keep code clean; unused locals are almost always a bug or leftover. (Unused globals are allowed.)
🪶 Feynman Reflection¶
A variable is a labeled box that always starts with a sensible default (its zero value). Constants are fixed values known at compile time; iota is a counter that auto-numbers a list of constants so you don't hand-write 0, 1, 2, ….
🕳️ Knowledge Gaps¶
- Typed-constant overflow rules — revisit with the types day.
✅ Summary¶
I can declare variables/constants idiomatically, rely on zero values, and build enums and flags with iota.
⏭️ Next Steps / Prep for Tomorrow¶
- Day 003: numeric & string types, conversions,
strconv.
| Time spent | Difficulty | Confidence |
|---|---|---|
| 90 min | 🟦⬜⬜⬜⬜ | 🟦🟦🟦⬜⬜ |
Suggested commit: feat(examples): variables, constants, and iota (day 002)