Range loops (for-each loops)

yourbasic.org/golang

Range statements iterate over slices, arrays, strings, maps or channels.

Basics

a := []string{"Foo", "Bar"}
for i, s := range a {
    fmt.Println(i, s)
}
0 Foo
1 Bar

Strings

For a string, the loop iterates over Unicode code points.

for i, ch := range "日本語" {
    fmt.Printf("%#U starts at byte position %d\n", ch, i)
}
U+65E5 '日' starts at byte position 0
U+672C '本' starts at byte position 3
U+8A9E '語' starts at byte position 6

Maps

The iteration order over maps is not specified and is not guaranteed to be the same from one iteration to the next.

m := map[string]int{
    "one":   1,
    "two":   2,
    "three": 3,
}
for k, v := range m {
    fmt.Println(k, v)
}
two 2
three 3
one 1

Channels

For channels, the iteration values are the successive values sent on the channel until closed.

ch := make(chan int)
go func() {
    ch <- 1
    ch <- 2
    ch <- 3
    close(ch)
}()
for n := range ch {
    fmt.Println(n)
}
1
2
3

Gotchas

Here are two traps that you might fall into when using range loops:

Share this page: