The 4 ways to write a range for loop

Go offers foreach loops for slices, arrays, strings, maps and channels.

Basic range loop iteration

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

Loop over string indexes and runes

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

Loop over map keys and values

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

Loop over 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
for n := range ch {

Range loop gotchas

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

Share this page: