The Go for loop: one loop to rule them all

Go has exactly one loop keyword: for. There’s no while, no do, no foreach. One keyword covers all of them, and in this lesson you’ll learn every form: the classic three-part loop, the “while” loop, the infinite loop, counting with range, and looping over strings, slices and maps. You’ll also learn break, continue and labels.

The three-part for loop

The classic form looks like the for loop from C, Java or JavaScript, minus the parentheses:

package main

import "fmt"

func main() {
	for i := 0; i < 5; i++ {
		fmt.Println(i)
	}
}Code language: Go (go)
0
1
2
3
4Code language: plaintext (plaintext)

The header has three parts, separated by semicolons:

  1. The init statement i := 0 runs once, before the loop starts. It usually declares a counter variable, which exists only inside the loop.
  2. The condition i < 5 is checked before every iteration. When it’s false, the loop ends.
  3. The post statement i++ runs after every iteration. i++ adds one to i; in Go it’s a statement, not an expression, so you can’t write x := i++.

The braces are required, and the opening brace goes on the same line as for. You can count in any step you like, for example backwards with for i := 10; i > 0; i -= 2.

The “while” loop

Leave out the init and post statements, and you’re left with just a condition. That’s a while loop, Go style:

package main

import "fmt"

func main() {
	n := 1
	for n < 100 {
		n *= 2
	}
	fmt.Println(n)
}Code language: Go (go)
128Code language: plaintext (plaintext)

The loop keeps doubling n as long as it’s below 100. Use this form when you don’t know in advance how many iterations you need. Because n is declared before the loop, it’s still available afterwards.

The infinite loop and break

Leave out the condition too, and the loop runs forever. You stop it from the inside with break, which exits the loop immediately:

package main

import "fmt"

func main() {
	n := 27
	steps := 0
	for {
		if n == 1 {
			break
		}
		if n%2 == 0 {
			n /= 2
		} else {
			n = 3*n + 1
		}
		steps++
	}
	fmt.Println("reached 1 after", steps, "steps")
}Code language: Go (go)
reached 1 after 111 stepsCode language: plaintext (plaintext)

(That’s the Collatz sequence: halve even numbers, triple odd numbers and add one. Nobody has proven it always reaches 1, which makes it a nice loop with no obvious end.) Besides break, a return also ends the loop, because it leaves the whole function. Infinite loops are common in servers and in programs that wait for input, where the loop really is meant to run until the program stops.

Counting with range

Since Go 1.22, you can range over an integer. for i := range n counts from 0 up to, but not including, n. It’s the shortest way to “do something n times”:

package main

import "fmt"

func main() {
	for i := range 3 {
		fmt.Println("round", i)
	}

	for range 2 {
		fmt.Println("hip hip hooray")
	}
}Code language: Go (go)
round 0
round 1
round 2
hip hip hooray
hip hip hoorayCode language: plaintext (plaintext)

If you don’t need the counter, leave it out with for range n. I use range n whenever I’d write for i := 0; i < n; i++, and keep the three-part form for anything fancier, like counting backwards or in steps.

Looping over strings, slices and maps

The range keyword also walks through collections. What you get on each iteration depends on what you range over. Slices and maps have their own lessons in stage 3, so here’s just a preview of each.

Slices

A slice is a list of values. Ranging over it gives you the index and a copy of the element:

package main

import "fmt"

func main() {
	fruits := []string{"apple", "banana", "cherry"}

	for i, fruit := range fruits {
		fmt.Println(i, fruit)
	}

	for _, fruit := range fruits {
		fmt.Println("I like", fruit)
	}
}Code language: Go (go)
0 apple
1 banana
2 cherry
I like apple
I like banana
I like cherryCode language: plaintext (plaintext)

Go refuses to compile unused variables, so when you only want the elements, put the blank identifier _ in place of the index. When you only want the index, write for i := range fruits.

Strings

As you saw in the strings lesson, ranging over a string gives you runes (characters) and their byte offsets, not individual bytes:

package main

import "fmt"

func main() {
	for i, r := range "Go!é" {
		fmt.Printf("%d:%c ", i, r)
	}
	fmt.Println()
}Code language: Go (go)
0:G 1:o 2:! 3:éCode language: plaintext (plaintext)

Maps

A map stores values by key. Ranging over it gives you each key and its value:

package main

import "fmt"

func main() {
	ages := map[string]int{"Alice": 31, "Bob": 25, "Carol": 40}

	for name, age := range ages {
		fmt.Println(name, "is", age)
	}
}Code language: Go (go)
Bob is 25
Carol is 40
Alice is 31Code language: plaintext (plaintext)

The order of a map loop is not defined, and Go deliberately varies it. Run the program twice and you may get a different order. Never rely on it; the maps lesson shows how to loop in sorted order.

range also works on arrays and on channels, which you’ll meet later.

break and continue

You’ve seen break, which leaves the loop. Its sibling continue skips the rest of the current iteration and jumps to the next one. Both work in every form of the loop:

package main

import "fmt"

func main() {
	for i := range 10 {
		if i%2 == 1 {
			continue // skip odd numbers
		}
		if i > 6 {
			break // stop completely
		}
		fmt.Println(i)
	}
}Code language: Go (go)
0
2
4
6Code language: plaintext (plaintext)

Labels for nested loops

In nested loops, break and continue affect only the innermost loop. To break out of an outer loop, put a label in front of it and name that label:

package main

import "fmt"

func main() {
	target := 12

outer:
	for a := 1; a <= 9; a++ {
		for b := 1; b <= 9; b++ {
			if a*b == target {
				fmt.Println("found:", a, "x", b)
				break outer
			}
		}
	}
	fmt.Println("done")
}Code language: Go (go)
found: 2 x 6
doneCode language: plaintext (plaintext)

Without the label, break would only stop the inner loop and the search would carry on with the next a. continue outer works the same way. Labels are also how you break out of a loop from inside a switch, because a plain break inside a switch only ends the switch. Use them sparingly; if you need them often, moving the loop into its own function and using return is usually clearer.

Each iteration gets a fresh variable

Since Go 1.22, every iteration of a loop gets its own copy of the loop variable. Before that, a for loop created the variable once and updated it on each pass. That difference matters when something keeps a reference to the variable after the iteration ends, such as a pointer:

package main

import "fmt"

func main() {
	var ptrs []*int
	for i := 0; i < 3; i++ {
		ptrs = append(ptrs, &i)
	}

	for _, p := range ptrs {
		fmt.Println(*p)
	}
}Code language: Go (go)
0
1
2Code language: plaintext (plaintext)

The first loop stores a pointer to i on each pass (append adds an element to a slice). With per-iteration variables, each pointer points to a different i, so you get 0, 1, 2. In older Go there was only one i, all three pointers pointed to it, and the program printed 3, 3, 3, because that’s where i ended up. The same bug used to bite people with goroutines and closures, and the Go team’s blog post on the change has the full story.

For you this means the intuitive behavior is the real one. The new semantics apply to modules that declare go 1.22 or later in their go.mod, which is every module you create with a current Go version. You’ll still see i := i lines in older code; they were the workaround and are no longer needed.

Practice

1. FizzBuzz. Print the numbers 1 to 15, but print Fizz for multiples of 3, Buzz for multiples of 5 and FizzBuzz for multiples of both. A tagless switch works nicely inside the loop.

Show a solution
package main

import "fmt"

func main() {
	for i := 1; i <= 15; i++ {
		switch {
		case i%15 == 0:
			fmt.Println("FizzBuzz")
		case i%3 == 0:
			fmt.Println("Fizz")
		case i%5 == 0:
			fmt.Println("Buzz")
		default:
			fmt.Println(i)
		}
	}
}Code language: Go (go)
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzzCode language: plaintext (plaintext)

2. Count the vowels. Loop over the string "Go is a fun language" with range and count the vowels (a, e, i, o, u, upper or lower case). Skip spaces with continue, and also count the letters that aren’t vowels.

Show a solution
package main

import "fmt"

func main() {
	vowels, others := 0, 0
	for _, r := range "Go is a fun language" {
		if r == ' ' {
			continue
		}
		switch r {
		case 'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U':
			vowels++
		default:
			others++
		}
	}
	fmt.Println("vowels:", vowels, "others:", others)
}Code language: Go (go)
vowels: 8 others: 8Code language: plaintext (plaintext)

Key takeaways

  • for is Go’s only loop: three-part (for i := 0; i < n; i++), condition-only (a while loop) and infinite (for { }).
  • for i := range n counts from 0 to n-1 (Go 1.22 and later).
  • range gives index and element for slices, byte offset and rune for strings, and key and value for maps (in no fixed order).
  • break leaves the loop, continue skips to the next iteration, and a label lets both target an outer loop.
  • Each iteration has its own loop variable, so pointers and closures captured in a loop behave the way you’d expect.