Lesson 7 of 38 · Fundamentals
Go for Loops: The Only Loop You Need
Repeating work is what computers do best: adding up gold, checking every letter of a password, running a game loop until the player quits. Many languages offer for, while and do-while for this.
Go has exactly one loop keyword — for — and it covers all of those jobs. In this lesson you will learn each form and when to use it.
The classic for loop
package main
import "fmt"
func main() {
for i := 1; i <= 3; i++ {
fmt.Println("Round", i)
}
}
Round 1
Round 2
Round 3
The header has three parts separated by semicolons: the init statement runs once before the loop starts, the condition is checked before every iteration, and the post statement runs after every iteration. Just like if, there are no parentheses but the braces are required. The variable i exists only inside the loop.
for as a while loop
Leave out the init and post statements, and for keeps looping as long as its condition is true — this is Go's while:
hp := 10
for hp > 0 {
hp -= 4
}
fmt.Println(hp) // -2
Infinite loops, break and continue
A for without any condition loops forever — until a break exits it. continue skips the rest of the current iteration and jumps straight to the next one:
package main
import "fmt"
func main() {
n := 0
for {
n++
if n%2 == 0 {
continue // skip even numbers
}
if n > 7 {
break
}
fmt.Print(n, " ")
}
fmt.Println()
}
1 3 5 7
range over an integer
Since Go 1.22, range over an integer n counts from 0 up to n-1 — the shortest way to repeat something n times:
for i := range 3 {
fmt.Println(i) // 0, then 1, then 2
}
range over a string
range over a string walks through its characters. Each iteration gives you the byte index where the character starts and the character itself as a rune — Go's type for a single Unicode character:
package main
import "fmt"
func main() {
for i, r := range "olé!" {
fmt.Println(i, string(r))
}
}
0 o
1 l
2 é
4 !
The index jumps from 2 to 4 because é takes two bytes. That is why you should use range to process text character by character: indexing with s[i] gives you single bytes and tears characters like é apart. Rune literals use single quotes, so you can write checks like r == 'é' or r >= 'a' && r <= 'z'.
When you don't need the index, ignore it with the blank identifier _: for _, r := range s. An unused i would be a "declared and not used" error.
Nested loops and labels
A loop can contain another loop. The inner loop runs completely for every iteration of the outer one:
for row := 1; row <= 3; row++ {
line := ""
for col := 1; col <= row; col++ {
line += "*"
}
fmt.Println(line)
}
*
**
***
break and continue only affect the innermost loop. To leave an outer loop from inside an inner one, put a label before the outer loop and name it: break grid (or continue grid):
package main
import "fmt"
func main() {
grid:
for row := range 3 {
for col := range 3 {
if row*col == 2 {
fmt.Println("found at", row, col)
break grid
}
}
}
}
found at 1 2
Common mistakes
- Off-by-one errors:
i < nandi <= ndiffer by one iteration. Check the first and last values of your loop variable. - Never-ending loops: a while-style loop must change something its condition depends on. (Here the runtime stops a program that runs too long.)
breakinside aswitch: it leaves only theswitch, not the surroundingfor. Use a label orreturn.- Looping over bytes instead of runes:
for i := 0; i < len(s); i++withs[i]treatséas two separate bytes.
Assignment
The function skeletons are given — put your code where the TODO comments are and use return to hand back the result.
SumTo(n int) intreturns the sum 1 + 2 + … + n.SumTo(5)is15. Fornless than 1 it returns0.Factorial(n int) intreturns n! = 1 × 2 × … × n.Factorial(5)is120, andFactorial(0)is1.nis never negative.CountVowels(s string) intcounts the vowelsa,e,i,oanduins, in lower or upper case.CountVowels("Gopher")is2.CollatzSteps(n int) intcounts how many steps the Collatz sequence needs to get fromndown to1. In each step, an evennbecomesn / 2and an oddnbecomes3*n + 1.CollatzSteps(6)is8(6 → 3 → 10 → 5 → 16 → 8 → 4 → 2 → 1) andCollatzSteps(1)is0.nis always at least 1.
Loops in other languages
- JavaScript Loops: for and while · JavaScript
- Python Loops: for, range() and while · Python
- Java Loops: for, while and do-while · Java
- C# Loops: for, while, do-while and foreach · C#
Need a quick reminder? The Go cheat sheet has every topic of Learn Go on one page.
Lesson last updated on .