How to use “range” in Golang

range iterates over elements in a variety of data structures. Let’s see how to use range with some of the data structures we’ve already learned.

Slice

Here we use range to for loop. From “range nums”, we got 2 values. 1st index of slice, 2nd value of slice at index

nums := []int{2, 3, 4}
sum := 0
for index, num := range nums {
       fmt.Println("index", index)
        sum += num
    }
fmt.Println("sum:", sum)

Map

Here we use range to for loop on map. From “range mapName”, we got 2 values. 1st key of map, 2nd value of map at key

In case You only want to get key, remove “, value” from code

In case You want to get value and ignore key, please replace “_” as key, and get only value

mapName := make(map[string]string)
mapName["a"] = "name of A"
mapName["b"] = "name of B"
for key, value := range mapName {
       fmt.Println("key-pair", key, value)
    }

for key := range mapName {
       fmt.Println("key", key)
    }

for _, value := range mapName {
       fmt.Println("value", value)
    }

View on github

PreNext