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 doesn't give me desired output.
What I really want is this:
Received ID: D1 Value: V1 Received ID: D2 Value: V2 Received ID: D3 Value: V3 Received ID: D4 Value: V4 Received ID: D5 Value: V5 Data key: D1 Value: UpdatedData for D1 Data key: D2 Value: UpdatedData for D2 Data key: D3 Value: UpdatedData for D3 Data key: D4 Value: UpdatedData for D4 Data key: D5 Value: UpdatedData for D5 Data key: D1 Value: UpdatedData for D1 Data key: D2 Value: UpdatedData for D2 Data key: D3 Value: UpdatedData for D3 Data key: D4 Value: UpdatedData for D4 Data key: D5 Value: UpdatedData for D5
To update value for a key in Map in Go language, assign the new value to map[key] using assignment operator. If the key we are updating is already present, then the corresponding value is updated with the new value.
In Go language, a map is a powerful, ingenious, and versatile data structure. Golang Maps is a collection of unordered pairs of key-value. It is widely used because it provides fast lookups and values that can retrieve, update or delete with the help of keys. It is a reference to a hash table.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With