How to use range in Go

Created
Modified

For-each Loop (slice or map)

The range form of the for loop iterates over a slice or map.

When ranging over a slice, two values are returned for each iteration. The first is the index, and the second is a copy of the element at that index.

package main

import "fmt"

func main() {

  var pow = []int{1, 2, 4, 8, 16, 32}

  for i, v := range pow {
    fmt.Printf("%d = %d\n", i, v)
  }
}
0 = 1
1 = 2
2 = 4
3 = 8
4 = 16
5 = 32

Iterating over a string

For strings, the range loop iterates over Unicode code points.

package main

import "fmt"

func main() {

  for i, ch := range "abc言語" {
    fmt.Printf("%#U position %d\n", ch, i)
  }
}
U+0061 'a' position 0
U+0062 'b' position 1
U+0063 'c' position 2
U+8A00 '言' position 3
U+8A9E '語' position 6

Iterating over a map

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

package main

import "fmt"

func main() {

  m := map[string]int64{
    "UTC": 0 * 60 * 60,
    "BST": 1 * 60 * 60,
    "CST": -6 * 60 * 60,
  }

  for i, v := range m {
    fmt.Printf("%s => %d\n", i, v)
  }
}
UTC => 0
BST => 3600
CST => -21600

Iterating over channels

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

package main

import "fmt"

func main() {

  ch := make(chan int)
  go func() {
    ch <- 1
    ch <- 3
    ch <- 5
    close(ch)
  }()

  for n := range ch {
    fmt.Println(n)
  }
}
1
3
5

Iterate over a range of integers

If you want to just iterate over a range w/o using and indices or anything else. No extra declaration needed, no _.

package main

func main() {

  for range [5]int{} {
    // Body...
  }

}

Related Tags