Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update map values in Go

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
like image 442
Mehulkumar Avatar asked Mar 10 '17 11:03

Mehulkumar


People also ask

How do you update maps in Go?

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.

How does map work in Go?

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.


1 Answers

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.

like image 143
icza Avatar answered Sep 19 '22 04:09

icza