For Loops
Go has one loop word: for.
You use it for counted loops, while-style loops, and forever loops.
You also use it to walk slices, maps, strings, and channels.
Learn for well and you cover almost all repetition in Go.
Classic three-part for
Init runs once at the start.
Condition is checked each round.
Post runs after each round.
Leave out any part you do not need.
While-style loop
Write for condition { ... } for a while-style loop.
It keeps going while the check is true.
Forever loop and break
Write a bare for for a loop that keeps going.
Exit with break when you are ready.
Think of a hamster wheel with an emergency stop button.
continue
continue skips the rest of this round.
Then the loop starts the next round.
Range over a slice
range gives the index and the value.
Use _ to ignore something you do not need.
This is clearer than counting indexes by hand.
Use range when walking collections. It is clearer than counting by hand.
Test yourself
Three quick questions made just for this lesson. Earn 10 XP per correct answer.