Day 004 — Control Flow (if / for / switch)¶
Month 1 · Week 1 · ⬅ Day 003 · Day 005 ➡ · Journal index
🎯 Learning Objective¶
Use Go's three control structures fluently and solve FizzBuzz cleanly.
📚 Topics¶
ifwith init statement ·for(the only loop) ·switch(no fall-through)
📖 Reading / Sources¶
- Learning Go ch.4
- Tour of Go — Flow control
📝 Notes¶
foris the only loop keyword. Forms: classicfor i:=0; i<n; i++, while-stylefor cond {}, infinitefor {}, andfor range.ifcan carry an init statement:if v := f(); v > 0 { … }—vis scoped to the if/else. Keeps scope tight.switchhas no implicit fall-through (the opposite of C). Cases break automatically; usefallthroughrarely. A bareswitch {}with boolean cases is a cleanif/else ifchain.- Cases can list multiple values:
case "Sat", "Sun":. - No parentheses around conditions; braces are mandatory.
💻 Code Examples¶
switch {
case n%15 == 0: return "FizzBuzz"
case n%3 == 0: return "Fizz"
case n%5 == 0: return "Buzz"
default: return strconv.Itoa(n)
}
Full code:
examples/control-flow/main.go· FizzBuzz:exercises/.../fizzbuzz
🏋️ Exercises / Practice¶
| Exercise | Status | Link |
|---|---|---|
| FizzBuzz (1..n) + tests | ✅ | fizzbuzz |
Sum/even-odd with if init |
✅ | examples/control-flow |
🐛 Mistakes Made¶
- Put the
%15check after%3/%5first time → numbers like 15 printed "Fizz". Order matters: check the most specific case first. - Reached for a
whilekeyword out of habit — it doesn't exist;for cond {}is the equivalent.
❓ Open Questions¶
- When is
fallthroughactually useful? (Rare — mostly grouping; multiple values per case is usually better.)
🧠 Active Recall¶
- Q: How many loop keywords does Go have, and what are the forms?
A
One:for. Forms — three-part, while-style (for cond), infinite (for {}), andfor range. - Q: Does a Go
switchfall through by default?A
No. Each case breaks automatically; opt in withfallthrough.
🪶 Feynman Reflection¶
Go simplifies control flow: one loop keyword for everything, if that can declare a throwaway variable, and a switch that won't surprise you by falling through. FizzBuzz is just "check divisibility, most specific first."
🕳️ Knowledge Gaps¶
for rangeover channels/maps — comes later (maps Day 011, channels Month 3).
✅ Summary¶
Comfortable with all control flow; FizzBuzz solved and tested.
⏭️ Next Steps / Prep for Tomorrow¶
- Day 005: functions, multiple returns,
defer, closures.
| Time spent | Difficulty | Confidence |
|---|---|---|
| 90 min | 🟦⬜⬜⬜⬜ | 🟦🟦🟦🟦⬜ |
Suggested commit: feat(exercises): control flow and FizzBuzz (day 004)