Explain the use of Go's range keyword for iterating over collections?
In Go, the range keyword is used to iterate over collections such as arrays, slices, maps, and channels. It provides a convenient way to iterate over the elements of a collection without having to manually manage the indexing or iteration variables.
The syntax for using **range**
is as follows:
for index, value := range collection {
// do something with index and value
}
In this syntax, **index**
is the index of the current element in the collection, and **value**
is the value of the current element. The type of **index**
depends on the type of the collection. For example, if the collection is an array or a slice, **index**
is an integer, whereas if the collection is a map, **index**
is the key type of the map.
Here's an example of using **range**
to iterate over a slice of strings:
fruits := []string{"apple", "banana", "orange"}
for index, value := range fruits {
fmt.Printf("Index: %d, Value: %s\n", index, value)
}
This would output:
Index: 0, Value: apple
Index: 1, Value: banana
Index: 2, Value: orange
Note that you can also use **_**
in place of **index**
or **value**
if you don't need that variable:
for _, value := range collection {
// do something with value only
}
Finally, it's worth noting that you can also use **range**
to iterate over the runes (Unicode code points) in a string, as follows:
for index, runeValue := range "Hello, 世界" {
fmt.Printf("Index: %d, Rune: %c\n", index, runeValue)
}
This would output:
Index: 0, Rune: H
Index: 1, Rune: e
Index: 2, Rune: l
Index: 3, Rune: l
Index: 4, Rune: o
Index: 5, Rune: ,
Index: 6, Rune:
Index: 7, Rune: 世
Index: 10, Rune: 界