The range keyword is mainly used in for loop to iterate over items of an array, slice, channel or map. With maps, this returns the key of the following key-value pair. With slice,range returns either one ortwo values for each iteration. The first one is the index and second one is the copy of the element at that index. With array, it returns the index of the item as integer.
CODE/PROGRAM/EXAMPLE
package main
import"fmt"
func main(){
/* create a slice */
numbers :=[]int{1,3,5,7,9,11
}
/* print the numbers */
fori:=range numbers {
fmt.Println("Slice item",i,"is",numbers[i])
}
/* create a map*/
countryCapitalMap :=map[string]string{"France":"Paris","India":"New Delhi","Japan":"Tokyo"}
/* print map using keys*/
forcountry :=range countryCapitalMap {
fmt.Println("Capital of",country,"is",countryCapitalMap[country])
}
/* print map using key-value*/
forcountry,capital :=range countryCapitalMap {
fmt.Println("Capital of",country,"is",capital)
}
}
Output :
Slice item 0 is 1
Slice item 1 is 5
Slice item 2 is 7
Slice item 3 is 9
Slice item 4 is 11