Go deliberately has exactly one looping keyword — there's no while, no do-while — because for alone, with different pieces omitted, already covers every one of those shapes.
2 min read
age := 20
if age >= 18 {
fmt.Println("Can vote")
} else {
fmt.Println("Too young")
}Conditions never need parentheses (if age >= 18, not if (age >= 18)) —
Go's syntax deliberately drops them. A second, very idiomatic form lets you
scope a variable to just the if/else blocks:
if err := doSomething(); err != nil {
fmt.Println("failed:", err)
}
// err doesn't exist out here — it was scoped to the if statementThis pattern — declare a variable, immediately check a condition on it, and have it disappear once the block ends — shows up constantly in Go's error-handling style from the earlier error-handling lesson.
Go has exactly one loop keyword. Every shape another language would use
while or do-while for is written with for, just omitting different
parts:
// The classic three-part form (init; condition; post)
for i := 0; i < 5; i++ {
fmt.Println(i)
}
// Condition only — this IS Go's "while" loop
count := 0
for count < 3 {
count++
}
// No condition at all — an infinite loop (common with an explicit break)
for {
if done {
break
}
}
// Iterating a collection
for index, value := range []string{"a", "b", "c"} {
fmt.Println(index, value)
}range is the idiomatic way to iterate over a slice, map, string, or
channel — it returns an index and value pair for a slice, or a key and
value pair for a map. If you only need the value, the index can be
discarded with _ (Go's "I'm intentionally ignoring this" convention):
for _, value := range items.
switch day {
case "Saturday", "Sunday":
fmt.Println("Weekend")
default:
fmt.Println("Weekday")
}Unlike C-family switch statements, Go's case doesn't fall through to
the next case by default — each case automatically breaks after running,
which removes an entire, very common class of "forgot the break statement"
bug from other languages. Falling through on purpose is still possible with
an explicit fallthrough keyword, but it has to be requested, not
accidentally triggered by omission.
Having one loop keyword instead of three isn't a missing feature — it's a
deliberate simplicity choice matching this domain's very first lesson (Go's
philosophy of a small language). Once for condition {} clicks as "this is
just while, spelled differently," and switch's automatic break stops
feeling surprising, reading real Go code gets noticeably faster, since
there's exactly one shape to recognize for looping instead of several.
Check your understanding
A quick comprehension check — not tracked, not graded, just for you.
1. Why does Go have only one looping keyword, `for`, instead of separate while and do-while keywords?
2. What happens after a matching case runs in a Go switch statement, by default?
3. What does `if err := doSomething(); err != nil {}` accomplish that a plain `if err != nil` couldn't?
Go