Loops in Go
Learn how loops work in Go: for, for range, simulating while and do-while, break and continue, and how to choose the right loop.
Introduction to Loops
A loop runs the same block of code multiple times. Instead of repeating code, a loop repeats it automatically based on a condition or by iterating over a collection.
1. Why Loops Are Needed
Loops remove repetition.
for Loop
Go has a single for loop that can act as a classic for, a while, or (with range) an iterator. The classic form has initialization, condition, and post statement.
1. How a for Loop Works
Initialization runs once; condition is checked before each iteration; post runs after each iteration.
2. Traversing a Slice by Index
Use the index to access each element.
while Loop
Go has no while keyword. Use for with a single condition: for condition { }.
1. How while-Style Loop Works
Condition is checked before each iteration.
Simulating do-while
To guarantee at least one execution, run the body once (or use a helper), then use a for loop for the rest.
1. do-while Style with for
Body runs first; condition is checked after.
for range (Values)
for range over a slice or string gives the index and the value (or just the value). No manual index needed.
1. for range over a Slice
Each iteration gives index and value.
for range over Maps
for range over a map yields key and value for each entry. Iteration order is not guaranteed.
1. for range over a Map
Key-value iteration.
break & continue
break exits the loop immediately. continue skips the rest of the current iteration and continues with the next.
1. break
Exit the loop immediately.
2. continue
Skip the rest of the current iteration.
Guard Clauses in Loops
Use continue to skip invalid or unwanted values at the start of the loop body.
1. Guard Clause with continue
Skip invalid data early.
Best Practices
Prefer for range when you do not need the index. Use classic for for index-based or reverse loops. Use for condition for while-style logic.
1. Loop Selection Guidelines
Rules of thumb.
Reverse for Loop
Use a for loop that starts at a higher value and decrements until the condition fails.
1. Reverse for Loop
Count down instead of up.
do-while vs while
A do-while runs at least once. In Go, use for { body; if condition { break } } or run the body once then use a for loop.
1. do-while Style with for
Force one execution, then use condition.
Range over Slices and Strings
for range over a slice gives index and value. Over a string it gives byte index and rune. Use for _, r := range s for runes.
1. Range over Slice (index and value)
Loop without manual index management.
2. Range over String (runes)
Iterate over Unicode code points, not bytes.
Range over Maps
Maps are the Go equivalent of key-value collections. for range over a map gives key and value; order is not guaranteed.
1. Range over Map
Key and value each iteration.
2. Range over Map (keys only or values only)
Use _ to skip key or value.