Skip to content

Go Range

The range keyword is used to iterate over elements in a variety of data structures. It's Go's universal "for-each" loop.

1. Range over Slices

When ranging over a slice, it returns two values: the index and a copy of the element at that index.

package main
import "fmt"

func main() {
    nums := []int{2, 3, 4}
    sum := 0
    for _, num := range nums {
        sum += num
    }
    fmt.Println("sum:", sum)

    for i, num := range nums {
        if num == 3 {
            fmt.Println("index:", i)
        }
    }
}

2. Range over Maps

For maps, range iterates over key/value pairs.

1
2
3
4
5
6
7
8
9
kvs := map[string]string{"a": "apple", "b": "banana"}
for k, v := range kvs {
    fmt.Printf("%s -> %s\n", k, v)
}

// Range over keys only
for k := range kvs {
    fmt.Println("key:", k)
}

3. Range over Strings

Ranging over a string iterates over Unicode code points (runes). The first value is the starting byte index of the rune, and the second is the rune itself.

1
2
3
4
5
for i, c := range "go" {
    fmt.Println(i, c)
}
// 0 103 (g)
// 1 111 (o)

Summary Table

Data Structure 1st Return Value 2nd Return Value
Array/Slice Index (int) Value (type)
Map Key (type) Value (type)
String Index (int) Rune (rune)
Channel Value (type) (None)