VOOZH about

URL: https://www.geeksforgeeks.org/go-language/range-keyword-in-golang/

⇱ Range Keyword in Golang - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Range Keyword in Golang

Last Updated : 12 Jul, 2025
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:
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:
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:
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.
Comment
Article Tags:

Explore