Stage 1 · Code
Variables, Types & Control Flow
for Loops
Go has only one loop keyword — for — but it covers every looping pattern you need: counted, condition-only, range, and infinite.
The Counted for Loop
The classic three-part for has an initializer, a condition, and a post statement separated by semicolons. The initializer runs once, the condition is checked before every iteration, and the post statement runs after each body.
There is no while, do-while, or foreach in Go. The single for keyword handles all patterns. This keeps the language small and consistent — once you know for, you know every loop.
Condition-Only Loop
When you omit the init and post statements, for becomes a while-style loop that runs as long as the condition is true. Omit the condition entirely to write an infinite loop — pair it with break to exit.
range Loops
range iterates over slices, arrays, maps, strings, and channels. It yields an index and a value on each iteration. You can discard either with the blank identifier _.
break and continue
break exits the innermost loop immediately. continue skips the rest of the current iteration and jumps to the next one. Both can be used with labels to target outer loops when you have nested loops.
Nested Loops
You can place a loop inside another loop. The inner loop runs to completion for every single iteration of the outer loop. Nested loops are commonly used for grids, tables, and pair-wise comparisons.
Every nested loop multiplies the work. Two loops over 1,000 items each means 1,000,000 iterations. For most small programs this is fine, but as you advance you will learn to reach for maps or sort-based approaches instead of checking every possible pair.
for init; cond; post {}— counted loop with a control variable.for cond {}— while-style; runs as long as the condition is true.for {}— infinite loop; usebreakorreturnto exit.for i, v := range slice {}— iterates with index and value.for _, v := range slice {}— discards the index with_.breakexits the loop;continuejumps to the next iteration.- Labels allow
breakandcontinueto target an outer loop.
Mark this lesson complete to store local progress and unlock a cleaner resume path the next time you visit.