Repeating Things
Repeating Things
Loops let you run the same code multiple times. Go has one loop keyword: for. It handles everything.
The classic for loop
The most common form has three parts separated by semicolons:
for i := 0; i < 5; i++ {
fmt.Println(i)
}
// Output: 0, 1, 2, 3, 4
Here's what each part does:
i := 0— init: runs once before the loop startsi < 5— condition: checked before each iteration. If false, the loop stopsi++— post: runs after each iteration (adds 1 toi)
So this loop starts i at 0, prints it, adds 1, checks if it's still less than 5, and repeats.
Return early, fall back after the loop
Loops get useful when you check something on each iteration. A loop that's searching for a value often wants two exits: return as soon as you find a match, and return a fallback value after the loop if you never did.
func firstMultiple(target, limit int) int {
for i := 1; i < limit; i++ {
if i%target == 0 {
return i
}
}
return -1 // nothing matched
}The return -1 only runs when the loop finishes without finding a match. That's the fallback.
Watch out for this bug: putting the fallback inside an else.
// BUG: exits on the first iteration every time
for i := 1; i < limit; i++ {
if i%target == 0 {
return i
} else {
return -1
}
}The else branch runs on iteration 1 and returns before the loop can check any other value. The failure case belongs after the loop, not paired with the success case.
Exercise: Retry
Imagine you're retrying a network request. A variable result is already declared at the top of the function as an empty string "", and the function already returns it for you.
Your job:
- Write a
forloop that runs fromi = 0up to (but not including)maxRetries. - Inside the loop, if
iequalssuccessOn, setresult = "success". - After the loop, if
resultis still"", setresult = "failed".
Examples:
retry(2, 5)→ succeeds on attempt 2,resultbecomes"success"retry(6, 5)→ only tries 0 to 4, never reaches 6,resultbecomes"failed"retry(0, 3)→ succeeds on first attempt,resultbecomes"success"