Go by Example

Range over Built-in Types

The range keyword iterates over slices, maps, strings, channels, and integers - each with different iteration semantics worth knowing.

range is a loop form for visiting items in a collection, such as an array, slice or map. It returns an index and value for arrays and slices, a key and value for maps, and a byte position and rune for strings. A channel passes values between goroutines, function calls started with go that can run while their caller continues. Ranging over a channel receives each value until the channel closes. Since Go 1.22, ranging over an integer produces values from zero to one less than that number.

The loop variables depend on the value after range. For a string, the index is the byte position where each rune begins, and the value is the decoded rune.

package main
 
import "fmt"
 
func main() {
    for i, v := range []int{4, 7} {
        fmt.Println(i, v)
    }
 
    scores := map[string]int{"Ada": 10, "Lin": 12}
    for name, score := range scores {
        fmt.Println(name, score)
    }
 
    for i, r := range "é!" {
        fmt.Printf("%d %c\n", i, r)
    }
 
    for i := range 3 {
        fmt.Println(i)
    }
 
    ch := make(chan string, 1)
    ch <- "ready"
    close(ch)
    for v := range ch {
        fmt.Println(v)
    }
}

In production

Maps do not promise a particular order, so sort their keys when output must always look the same. A string's index moves by the number of bytes in each rune, while len(s) counts bytes. See Strings and Runes for how Go handles text.

Enjoyed this? Get more software craft delivered to your inbox.