I want to build a map with string key and struct value with which I\'m able to update struct value in the map identified by map key.
I\'ve tried this and this which
You can't change values associated with keys in a map, you can only reassign values.
This leaves you 2 possibilities:
Store pointers in the map, so you can modify the pointed object (which is not inside the map data structure).
Store struct values, but when you modify it, you need to reassign it to the key.
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.
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.