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 |
1 | ~ go run example.go |
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 } |
1 | 0) 1 |
Exercises
- What is the purpose of
range
? - What the difference between the line
for index, element := range a
and the linefor _, element := range a
?
Leave a Reply