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.
odd = 1 odd = 3 odd = 5 odd = 7 odd = 9 odd = 11 odd = 13
Here, all the elements are printed with their respective index.
strng = 71 strng = 101 strng = 101 strng = 107 strng = 115 strng = 102 strng = 111 strng = 114 strng = 71 strng = 101 strng = 101 strng = 107 strng = 115
Here, the items printed is the rune, that is int32 ASCII value of the stated characters that forms string.
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.