Reading — step 1 of 5
Learn
If, Else, Switch
Go's control flow is deliberately boring — and then it hands you two constructs most languages don't have: the if-with-statement and a switch that quietly replaces half the if/else chains you'd otherwise write.
if and else
Two syntax rules, both enforced by the compiler:
- No parentheses around the condition (
if (x > 5)compiles butgofmtstrips the parens — they're noise). - Braces always, even for one-liners. The
if (x) doThing();bug class — where a second "indented" line silently isn't in the if — cannot be written in Go.
And one type rule with teeth: the condition must be a bool. Not an int, not a non-empty string — if 1 { is a compile error. No truthiness means no memorizing what counts as falsy.
The if-with-statement idiom
if can run a short statement first, scoping its variables to the if/else only:
This is the Go idiom — do a thing, check how it went, all in one line, without leaking temporary variables into the rest of the function. You'll meet it on nearly every function that returns an error (chapter 4), so let your eyes get used to the shape now.
switch: better than you remember
Go's switch fixed the C design:
- No fallthrough by default. Each case breaks on its own; forgetting
breakcan't hurt you because there is nobreak. (An explicitfallthroughkeyword exists for the rare day you want it.) - Cases take lists (
case "Sat", "Sun"), which kills a whole family of duplicated branches. - No condition at all turns switch into a cleaner if/else chain:
The first true case wins, top to bottom. Any time you find yourself stacking three or more else ifs, this form reads better — and it's what experienced Go reviewers will suggest.
Your exercise: FizzBuzz for one number
The classic rules: multiples of 3 print Fizz, of 5 print Buzz, of both print FizzBuzz, otherwise print the number. One trap contains the entire lesson: check "divisible by both" first. Test 3-divisibility before 15-divisibility and 15 prints Fizz — the 15 case is unreachable, because the first true branch wins and evaluation stops. Order of cases is logic. (Elegant checks: n%15 == 0 is "divisible by both," and %d prints the fallthrough number.) Whether you write it as if/else or a bare switch, make the most specific condition come first — that principle will follow you far past FizzBuzz.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…