iterate over map values and change them in go

To iterate over map values and modify them in Go, we first need to create a map with some key-value pairs. Then we can use a for loop to iterate over the values of the map.

main.go
package main

import "fmt"

func main() {
    myMap := map[string]int{
        "apple": 5,
        "banana": 3,
        "orange": 2,
    }

    // iterate over map values
    for key, value := range myMap {
        fmt.Println(key, value)
        
        // modify value
        myMap[key] = value + 1
    }
    
    fmt.Println(myMap)
}
339 chars
22 lines

In the above code, we are using a for loop with range to iterate over the key-value pairs of the myMap map. We are then printing each key-value pair using fmt.Println. Finally, we are modifying the value of the key by incrementing it by 1.

Note that when we modify the value of the key, we are using the key variable to access the map value because the value variable contains a copy of the value and not a reference to the original map value. Therefore, we need to use the key to modify the value in the map.

gistlibby LogSnag