Loop Variations
Loop Variations
You've seen the classic for loop. Go's for keyword has a few other shapes you'll run into all the time.
While-style loop
If you only need a condition, drop the init and post:
count := 3
for count > 0 {
fmt.Println(count)
count--
}
// Output: 3, 2, 1
This works like a while loop in other languages. It keeps running as long as the condition is true. Use it when you don't know up front how many iterations you'll need.
Infinite loop
Drop everything and the loop runs forever. Use break to exit:
n := 1
for {
if n > 100 {
break
}
n *= 2
}
fmt.Println(n) // 128
Infinite loops are common in servers and event handlers — anywhere the program runs until something tells it to stop.
Range loop
When you want to repeat something a fixed number of times, range is the cleanest way:
for i := range 5 {
fmt.Println(i) // 0, 1, 2, 3, 4
}range over an integer counts from 0 to n-1. Later you'll use range to loop over slices and maps too.
Exercise: Compound Interest
You're building a savings projection. Given a starting balance and a number of years, calculate the final balance after applying 10% interest every year.
Each year the balance grows by 10% of itself: balance += balance / 10.
Use a range loop to iterate over the years: for range years { ... }. You don't need the index, just the count.
Examples:
futureBalance(1000, 0)→1000(no years, no growth)futureBalance(1000, 1)→1100futureBalance(1000, 2)→1210futureBalance(1000, 5)→1610