Go Range
The range keyword makes a for loop walk over every element of a collection. What it yields depends on what you range over:
| Range over | First value | Second value |
|---|---|---|
| array or slice | index | copy of the element |
| string | byte index of each rune | the rune (character) |
| map | key | value |
| channel | received value | — |
integer n |
0 … n-1 | — |
| function iterator (Go 1.23+) | whatever the iterator yields |
Slices and arrays
package main
import "fmt"
func main() {
planets := []string{"Mercury", "Venus", "Earth"}
for i, p := range planets {
fmt.Println(i, p)
}
// only the values: ignore the index with _
for _, p := range planets {
fmt.Print(p[:1], " ")
}
fmt.Println()
// only the index: leave out the second variable
for i := range planets {
fmt.Print(i, " ")
}
fmt.Println()
}0 Mercury
1 Venus
2 Earth
M V E
0 1 2
The value is a copy
The second variable receives a copy of each element. Changing it does not change the slice. To modify the elements, index into the slice.
package main
import "fmt"
func main() {
prices := []float64{10, 20, 30}
for _, p := range prices {
p *= 2 // only changes the copy
}
fmt.Println(prices)
for i := range prices {
prices[i] *= 2 // changes the real element
}
fmt.Println(prices)
}[10 20 30]
[20 40 60]
Strings
Ranging over a string decodes UTF-8 and gives you runes, not bytes. The index is the byte position where each rune starts, so it can jump by more than one.
package main
import "fmt"
func main() {
for i, r := range "Go€!" {
fmt.Printf("byte %d: %c (%U)\n", i, r, r)
}
}byte 0: G (U+0047)
byte 1: o (U+006F)
byte 2: € (U+20AC)
byte 5: ! (U+0021)
Maps
Ranging over a map gives you each key and value. The order is deliberately random and changes from run to run. When you need a stable order, collect the keys, sort them, and loop over the sorted keys.
package main
import (
"fmt"
"maps"
"slices"
)
func main() {
stock := map[string]int{"pears": 4, "apples": 12, "kiwis": 7}
total := 0
for _, qty := range stock { // order does not matter for a sum
total += qty
}
fmt.Println("total items:", total)
keys := slices.Sorted(maps.Keys(stock))
for _, k := range keys {
fmt.Println(k, stock[k])
}
}total items: 23
apples 12
kiwis 7
pears 4
maps.Keys returns an iterator over the keys and slices.Sorted collects it into a sorted slice — both arrived in Go 1.23.
Ranging over a function (iterators)
Since Go 1.23, range also accepts functions with the signature func(yield func(T) bool). The function calls yield for each value; if yield returns false the loop was stopped (for example by break) and the function should return.
package main
import "fmt"
// Evens yields the even numbers from 0 up to (not including) limit.
func Evens(limit int) func(yield func(int) bool) {
return func(yield func(int) bool) {
for n := 0; n < limit; n += 2 {
if !yield(n) {
return
}
}
}
}
func main() {
for n := range Evens(10) {
if n > 6 {
break
}
fmt.Print(n, " ")
}
fmt.Println()
}0 2 4 6
Tip: You will rarely write iterators yourself at first, but you will use them from the standard library:
maps.Keys,maps.Values,slices.Values,strings.SplitSeqand more.
Test yourself
What does for i, v := range []string{"a", "b"} give in i?
- The values
- The indexes 0 and 1
- The lengths
- Pointers to the elements
In what order does range visit the entries of a map?
- Insertion order
- Sorted by key
- Unspecified and randomised
- Sorted by value
What does the second variable contain when ranging over a string?
- A byte
- A rune (Unicode character)
- A one-letter string
- The byte length