golang tutorial - Golang Range | Range In Golang - golang - go programming language - google go - go language - go program - google language
Golang Range
- The range keyword is used in for loop to iterate over items of an array, slice, channel or map. With array and slices, it returns the index of the item as integer. With maps, it returns the key of the next key-value pair. Range either returns one value or two. If only one value is used on the left of a range expression, it is the 1st value in the following table.
Range-Expression | 1st value | 2nd value(optional) |
---|---|---|
Array or slice a [n]E | index i int | a[i] E |
String s string type | index i int | rune int |
map m map[K]V | key k K | value m[k] V |
channel c chan E | element e E | none |
Example
- Following is the example:
package main
import "fmt"
func main() {
/* create a slice */
numbers := []int{20,1,9,3,4,12,14,7,19}
/* print the numbers */
for i:= range numbers {
fmt.Println("Slice item",i,"is",numbers[i])
}
/* create a map*/
countryCurrencyMap := map[string] string {"UnitedStates":"Dollar","UnitedKingdom":"Pound","India":"Rupee"}
/* print map using keys*/
for country := range countryCurrencyMap {
fmt.Println("Currency of",country,"is",countryCurrencyMap[country])
}
/* print map using key-value*/
for country,Currency := range countryCurrencyMap {
fmt.Println("Currency of",country,"is",Currency)
}
}
click below button to copy the code. By - golang tutorial - team
- When the above code is compiled and executed, it produces the following result:
Slice item 0 is 20
Slice item 1 is 1
Slice item 2 is 9
Slice item 3 is 3
Slice item 4 is 4
Slice item 5 is 12
Slice item 6 is 14
Slice item 7 is 7
Slice item 8 is 19
Currency of France is Paris
Currency of Italy is Rome
Currency of Japan is Tokyo
Currency of France is Paris
Currency of Italy is Rome
Currency of Japan is Tokyo