In Golang Range keyword is used in different kinds of data structures in order to iterates over elements. The range keyword is mainly used in for loops in order to iterate over all the elements of a map, slice, channel, or an array. When it iterates over the elements of an array and slices then it returns the index of the element in an integer form. And when it iterates over the elements of a map then it returns the key of the subsequent key-value pair. Moreover, range can either returns one value or two values. Lets see what range returns while iterating over different kind of collections in Golang.
- Array or slice: The first value returned in case of array or slice is index and the second value is element.
- String: The first value returned in string is index and the second value is rune int.
- Map: The first value returned in map is key and the second value is the value of the key-value pair in map.
- Channel: The first value returned in channel is element and the second value is none.
Now, let’s see some examples to illustrate the usage of range keyword in Golang.
Example 1:
package main
import "fmt"
func main() {
odd := [7]int{1, 3, 5, 7, 9, 11, 13}
for i, item := range odd {
fmt.Printf( "odd[%d] = %d \n" , i, item)
}
}
|
Output:
odd[0] = 1
odd[1] = 3
odd[2] = 5
odd[3] = 7
odd[4] = 9
odd[5] = 11
odd[6] = 13
Here, all the elements are printed with their respective index.
Example 2:
package main
import "fmt"
func main() {
var string = "GeeksforGeeks"
for i, item := range string {
fmt.Printf( "string[%d] = %d \n" , i, item)
}
}
|
Output:
string[0] = 71
string[1] = 101
string[2] = 101
string[3] = 107
string[4] = 115
string[5] = 102
string[6] = 111
string[7] = 114
string[8] = 71
string[9] = 101
string[10] = 101
string[11] = 107
string[12] = 115
Here, the items printed is the rune, that is int32 ASCII value of the stated characters that forms string.
Example 3:
package main
import "fmt"
func main() {
student_rank_map := map[string]int{ "Nidhi" : 3,
"Nisha" : 2, "Rohit" : 1}
for student := range student_rank_map {
fmt.Println( "Rank of" , student, "is: " ,
student_rank_map[student])
}
for student, rank := range student_rank_map {
fmt.Println( "Rank of" , student, "is: " , rank)
}
}
|
Output:
Rank of Nidhi is: 3
Rank of Nisha is: 2
Rank of Rohit is: 1
Rank of Nidhi is: 3
Rank of Nisha is: 2
Rank of Rohit is: 1
So, here at first the output is printed only using key then again output is printed using both key and value.
Last Updated :
28 Jun, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...