The One Loop: for
Every way to repeat yourself in Go
Computers are champions at doing the same thing many times without getting bored. Where other languages have while loops, do loops, and more, Go has exactly one keyword for repetition: for. It just wears a few different outfits.
Outfit one: the counting loop
for i := 0; i < 5; i++ {
fmt.Println("Lap number", i)
}This prints lap numbers 0 through 4. The header has three parts separated by semicolons:
- Setup:
i := 0runs once, creating the counter. - Condition:
i < 5is checked before every lap. While it is true, the loop keeps going. - Step:
i++runs after every lap and means add 1 to i.
Counting from 0 feels odd at first, but it matches how lists are numbered in Go, so it quickly becomes natural.
Outfit two: the while-style loop
Drop the setup and step, keep only the condition, and for behaves like the while loop from other languages:
energy := 10
for energy > 0 {
fmt.Println("Still running! Energy:", energy)
energy = energy - 3
}The loop keeps going as long as the condition stays true. Something inside the loop must move toward making it false, or the loop will never end.
Outfit three: the forever loop
for {
fmt.Println("This would print forever...")
break
}A bare for loops forever. That sounds like a bug, but servers use exactly this shape: wait for a request, handle it, repeat forever. The break keyword jumps out of the loop immediately.
Two loop controls
breakleaves the loop right now.continueskips the rest of this lap and starts the next one.
for i := 1; i <= 10; i++ {
if i % 2 == 0 {
continue
}
fmt.Println(i)
}This prints only the odd numbers from 1 to 9: whenever i is even, continue skips the print.
If your program seems frozen, you probably wrote a loop whose condition never becomes false. Check that something inside the loop changes the values the condition looks at.
Quick check
Q1 How do you write a while-style loop in Go?
Q2 How many times does this loop print? for i := 0; i < 3; i++ { fmt.Println(i) }
Want to save your progress? It's free.
Create a free account