Skip to content

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

📝 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 = 5 works as int or float64 depending on use).
  • iota resets to 0 in each const block and increments by 1 per line — the idiomatic enum builder. Combine with 1 << iota for bit flags.
  • Unused local variables are a compile error (not a warning). Same for unused imports.

💻 Code Examples

type Permission uint8
const (
    Read    Permission = 1 << iota // 1
    Write                          // 2
    Execute                        // 4
)

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 → only var/const work 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)

  1. Q: What does iota equal on the 3rd line of a const block?
    A2 — it starts at 0 and increments by one per ConstSpec line in the block.
  2. Q: Why does Go reject an unused local variable?
    AIt'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)