Range

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.

range.go

  1. package main
  2. import "fmt"
  3. var pow = []int{1, 2, 4, 8, 16, 32, 64, 128}
  4. func main() {
  5. for i, v := range pow {
  6. fmt.Printf("2**%d = %d\n", i, v)
  7. }
  8. }