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.go339 chars22 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