The range keyword is used in for loop to iterate over objects of an array, slit, map or channel.
A few main points about the range:
- Range iterates over elements in various data structures.
- With array and slices, it returns the index of the element as an integer.
- In the case of maps, it returns the key of the upcoming key-value pair.
- Range either returns one value or 2.
- This is also called Go for range.
- A for loop is used to iterate over elements in an assortment of data structures (e.g., a piece, an array, a map, or a series ).
- It may be used to traverse every item in a collection.
- It’s comparable to foreach in different languages. However, we still have the index at each iteration in for range construct.
Syntax of Range in Go
The general way of using the range is:
for ind, val := range collection { //Statement to execute }
The Illustration of Go vary with string
The for-range loop may be used to access individual characters in a string.
The example below shows how:
package main import "fmt" func main() { for ind, val := range "Go Lang" { fmt.Printf("%#U position %d\n", val, ind) } }
Output:
U+0047 ‘G’ position 0
U+006F ‘o’ position 1
U+0020 ‘ ‘ position 2
U+004C ‘L’ position 3
U+0061 ‘a’ position 4
U+006E ‘n’ position 5
U+0067 ‘g’ position 6
Another basic example with string array
package main import "fmt" func main() { strarr := []string{"A", "Range", "Tutorial"} for ind, val := range strarr { fmt.Println(ind, val) } }
Output:
0 A
1 Range
2 Tutorial
Using range with map example
In this example, we have an employee salary map. There, we store the name of the employee and their salary.
Then we used the range and displayed the values as shown below:
package main import "fmt" func main() { //A map of employees and thier salary empSal := map[string] int {"Mike":5000,"Shaggy":3000,"Nana":2000} /* Displaying map using range*/ for emp := range empSal { fmt.Println("The Salary of ",emp,"is",empSal[emp]) } }
Output:
The Salary of Shaggy is 3000
The Salary of Nana is 2000
The Salary of Mike is 5000
Example with an array slice
The code:
package main import "fmt" func main() { nums := []int{5,10,15,20,25} for ind:= range nums { fmt.Println("Element",ind,"is",nums[ind]) } }
Output
Element 0 is 5
Element 1 is 10
Element 2 is 15
Element 3 is 20
Element 4 is 25
An example with channel
The final example shows using the range with a channel in Go language.
package main import "fmt" func main() { aChannel := make(chan int) go func() { aChannel <- 5 aChannel <- 10 aChannel <- 15 aChannel <- 20 close(aChannel) }() for val := range aChannel { fmt.Println(val) } }
The output:
5
10
15
20