Go Has a Single Loop Keyword, for
Go has no while or do-while: every loop is written with for, in one of four shapes. Its if drops the parentheses around the condition but always requires braces. Fewer forms means less to remember, as long as you know which shape replaces which classic loop.
The Four Shapes of for
for i := 0; i < len(names); i++ { } // C-style counter
for count < 10 { } // condition only: Go's "while"
for { } // infinite loop, left with break or return
for i, n := range numbers { } // index and value over a slice, map, string or channel
for _, n := range numbers { } // discard the index with _
if Without Parentheses, with an Optional Init Statement
if err := save(u); err != nil {
return err
}
The short statement before the condition (err := save(u)) limits err to the if and its else, which is the idiomatic way to handle errors.
References
- Programming Languages MOC - hub for language notes.
- A Tour of Go: For - the loop forms, including "for is Go's while".
- Effective Go: Control structures -
ifwith init statements andrange.
Review cards
Flashcard How do you write a while loop in Go?
With for and only a condition: for count < 10 { }. Go has no while keyword; a bare for { } loops forever.
Flashcard In for _, u := range users { u.Age++ }, why doesn't the slice change?
u is a copy of each element. Modify through the index instead: users[i].Age++.