Go range
In Go, the range (a form of for loop) is used to iterate over elements of various data structures such as an array, string, map, etc.
In a lot of programming languages, such as C, the following pattern to iterate over an array is very common:
for (int i = 0; i < n; i++) {
v = x[i];
// do something with v
}
In Go (and, for example, in Python, where there is an enumerate
function), there is a better way to do this. It is called a range
and it is used like this:
for i, v := range x {
// do something with v
}
Find the average of numbers
Let us write a function to find the average
of numbers, you can recognize the pattern we just described.
func average(x []float64) float64 {
var sum float64 = 0
for i := 0; i < len(x); i++ {
sum += x[i]
}
return sum / float64(len(x))
}
Here is instead the idiomatic version using a range
:
func average(x []float64) float64 {
var sum float64 = 0
for _, v := range x {
sum += v
}
return sum / float64(len(x))
}
Here _
is a special variable name that means "I don't care about this value".
Indeed, the index of the element is not used in the body of the loop, so we can just ignore it.
range over strings
You can also use ranges over strings. In this case, the value is a rune (which is a special word for a Unicode character).
package main
import "fmt"
func main() {
s := "Hello, 世界"
for i, r := range s {
fmt.Printf("%d %c\n", i, r)
}
}
Here is the output of this snippet:
0 H
1 e
2 l
3 l
4 o
5 ,
6
7 世
10 界
range over Arrays
We can use the for range loop to iterate over an array and access the individual index and element of an array. Let us take an example to demonstrate.
package main
import "fmt"
func main() {
// Declare and Initialize an array of numbers
numbers := [5]int{10, 20, 30, 40, 50}
// use range to iterate over the elements of an array
for index, num := range numbers {
fmt.Printf("index[%d] = %d \n", index, num)
}
}
Output
index[0] = 10
index[1] = 20
index[2] = 30
index[3] = 40
index[4] = 50
range over map
We can use the for range over the map to iterate over all the key-value pairs. Let us take an example to demonstrate.
package main
import "fmt"
func main() {
// create a map
products := map[string]float32{"iPhone": 7.7, "Oneplus": 9.2, "Samsung": 9.5}
fmt.Println("Product Overall Rating:")
// iterate the key-value pair using range
for item, score := range products {
fmt.Println(item, ":", score)
}
}
Output
Product Overall Rating:
iPhone : 7.7
Oneplus : 9.2
Samsung : 9.5