Repeating Things

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:

example.go
for i := 0; i < 5; i++ {
    fmt.Println(i)
}
// Output: 0, 1, 2, 3, 4

Here's what each part does:

  • i := 0init: runs once before the loop starts
  • i < 5condition: checked before each iteration. If false, the loop stops
  • i++post: runs after each iteration (adds 1 to i)

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.

example.go
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.

example.go
// 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

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:

  1. Write a for loop that runs from i = 0 up to (but not including) maxRetries.
  2. Inside the loop, if i equals successOn, set result = "success".
  3. After the loop, if result is still "", set result = "failed".

Examples:

  • retry(2, 5) → succeeds on attempt 2, result becomes "success"
  • retry(6, 5) → only tries 0 to 4, never reaches 6, result becomes "failed"
  • retry(0, 3) → succeeds on first attempt, result becomes "success"
Stuck? Reveal a hint to help you.
Hints (0/3)
Key Takeaway
Next UpOther shapes the for loop can take.