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:
:= []int{1,2,3,4,5,6} nums
Then iterate over it with range:
package main
import "fmt"
func main() {
:= []int{1,2,3,4,5,6}
nums
for _, num := range nums {
.Println(num)
fmt}
}
~ 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 {
.Print(index, ") ", element,"\n")
fmt}
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 linefor _, element := range a
?