How to update map values in Go

You can’t change values associated with keys in a map, you can only reassign values.

This leaves you 2 possibilities:

  1. Store pointers in the map, so you can modify the pointed object (which is not inside the map data structure).

  2. Store struct values, but when you modify it, you need to reassign it to the key.

1. Using pointers

Storing pointers in the map: dataManaged := map[string]*Data{}

When you “fill” the map, you can’t use the loop’s variable, as it gets overwritten in each iteration. Instead make a copy of it, and store the address of that copy:

for _, v := range dataReceived {
    fmt.Println("Received ID:", v.ID, "Value:", v.Value)
    v2 := v
    dataManaged[v.ID] = &v2
}

Output is as expected. Try it on the Go Playground.

2. Reassigning the modified struct

Sticking to storing struct values in the map: dataManaged := map[string]Data{}

Iterating over the key-value pairs will give you copies of the values. So after you modified the value, reassign it back:

for m, n := range dataManaged {
    n.Value = "UpdatedData for " + n.ID
    dataManaged[m] = n
    fmt.Println("Data key:", m, "Value:", n.Value)
}

Try this one on the Go Playground.

Leave a Comment