WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

Go - 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 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

The following paragraph shows how to use range
package main

import "fmt"

func main() {
    /* create a slice */
    numbers := []int{0,1,2,3,4,5}

    /* print the numbers */
    for i:= range numbers {
        fmt.Println("Slice item",i,"is",numbers[i])
    }

    /* create a map*/
    countryCapitalMap := map[string] string {"France":"Paris","USA":"Washington D.C.","India":"Delhi"}

    /* print map using keys*/
    for country := range countryCapitalMap {
        fmt.Println("Capital of",country,"is",countryCapitalMap[country])
    }

    /* print map using key-value*/
    for country,capital := range countryCapitalMap {
        fmt.Println("Capital of",country,"is",capital)
    }
}
When the above code is compiled and executed, it produces the following result
$go run main.go
Slice item 0 is 0
Slice item 1 is 1
Slice item 2 is 2
Slice item 3 is 3
Slice item 4 is 4
Slice item 5 is 5
Capital of France is Paris
Capital of USA is Washington D.C.
Capital of India is Delhi
Capital of France is Paris
Capital of USA is Washington D.C.
Capital of India is Delhi