For Loops in Go — The Only Loop You Need
Go has just one loop keyword. That's it. But it can do everything — and we'll show you how.
Also available on YouTube • 17:50 watch time
Why Loops Exist
Doing something once is easy. But what if you need to print numbers 1 through 100? Or process every item in a list? You're not going to write 100 print statements. Loops let you repeat a block of code as many times as you need — automatically.
The Classic For Loop
This is the pattern you'll use most often — start at a number, keep going while a condition is true, and increment after each round:
for i := 0; i < 5; i++ {
fmt.Println(i)
}
// Output: 0, 1, 2, 3, 4
Three parts separated by semicolons: init (i := 0), condition (i < 5), and post (i++). As long as the condition is true, the loop keeps running.
Using For as a While Loop
Most languages have a separate while keyword. Go doesn't — you just use for with only a condition:
count := 1
for count <= 5 {
fmt.Println(count)
count++
}
This keeps running as long as count is 5 or less. Same idea as a while loop, just written with for.
Looping Over Collections with Range
When you have a list of things and want to go through each one:
languages := []string{"Go", "Python", "JavaScript"}
for index, lang := range languages {
fmt.Printf("%d: %s\n", index, lang)
}
range gives you both the index (position) and the value at each step. If you don't need the index, replace it with an underscore: for _, lang := range languages.
The Infinite Loop
Sometimes you want a loop that runs forever — like a server waiting for requests. Just write for with nothing else:
for {
fmt.Println("Running...")
// Use break to exit when needed
}
Break and Continue: Use break to exit a loop early, and continue to skip the rest of the current iteration and jump to the next one. These work exactly like you'd expect.
Try It Yourself
Print the numbers 1 to 20. Then try printing only the even numbers. Finally, create a slice of your favorite foods and use range to print each one with its position.