Skip to content

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

  • if with init statement · for (the only loop) · switch (no fall-through)

📖 Reading / Sources

📝 Notes

  • for is the only loop keyword. Forms: classic for i:=0; i<n; i++, while-style for cond {}, infinite for {}, and for range.
  • if can carry an init statement: if v := f(); v > 0 { … }v is scoped to the if/else. Keeps scope tight.
  • switch has no implicit fall-through (the opposite of C). Cases break automatically; use fallthrough rarely. A bare switch {} with boolean cases is a clean if/else if chain.
  • 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 %15 check after %3/%5 first time → numbers like 15 printed "Fizz". Order matters: check the most specific case first.
  • Reached for a while keyword out of habit — it doesn't exist; for cond {} is the equivalent.

❓ Open Questions

  • When is fallthrough actually useful? (Rare — mostly grouping; multiple values per case is usually better.)

🧠 Active Recall

  1. Q: How many loop keywords does Go have, and what are the forms?
    AOne: for. Forms — three-part, while-style (for cond), infinite (for {}), and for range.
  2. Q: Does a Go switch fall through by default?
    ANo. Each case breaks automatically; opt in with fallthrough.

🪶 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 range over 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)