Range iterates over elements. That can be elements of an array, elements of a dictionary or other data structures.

When using range, you can name the current element and current index:
for i, num := range nums {.

But you are free to ignore the index: for _, num := range nums {.

Example

Range

Range is always used in conjunction with a data structure.
Thus, the first step is to create a data structure. Here we define a slice:

nums := []int{1,2,3,4,5,6}

Then iterate over it with range:

package main

import "fmt"

func main() {
nums := []int{1,2,3,4,5,6}

for _, num := range nums {
fmt.Println(num)
}
}
1
2
3
4
5
6
7
~ go run example.go
1
2
3
4
5
6

Index

You can use the index. This shows the current index in the data structure.
Instead of the underscore _, we named it index. That variable now contains the current index.

var a = []int64{ 1,2,3,4 }

for index, element := range a {
fmt.Print(index, ") ", element,"\n")
}
1
2
3
4
0) 1
1) 2
2) 3
3) 4

Exercises

  • What is the purpose of range ?
  • What the difference between the line for index, element := range a and the line for _, element := range a ?

Download Answers