-1
json.Unmarshal([]byte(byteValue), &result)

After json.Unmarshal, the result is a map[string]interface{}

I can manipulate the values of the map direcly with:

result["player"].(map[string]interface{})["inventory"].(map[string]interface{})["gold"]=100

But this is a long variable name, I want to appoint a pointer to adress of this and manipulate with a shorter name like:

gold:=&result["player"].(map[string]interface{})["inventory"].(map[string]interface{})["gold"]

Then manipulate only *gold.

Trying to do this, I get the error:

cannot take the address of result["player"].(map[string]interface {})["inventory"].(map[string]interface {})["gold"]

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
  • 4
    Map elements are not addressable. If you want to manipulate it this way you should strongly consider defining appropriate `struct` types to match the data. – Adrian May 18 '21 at 20:12
  • 1
    `"gold"` here is a number if some sort, so modifying a pointer to that value is not going to modify it in the map. Just assign the map to a temporary variable if you want to reuse it. – JimB May 18 '21 at 20:20
  • @Adrian, thanks for verifying what I suspected. At first it seems illogical that a value not to have a kind of variable that can be pointered but I think this is because maps are dynamic and memory adress can change. To have a struct was my first idea but the json I try to manipulate is dynamic and map was a better solution. Thank you indeed! – Ertunc Nese May 18 '21 at 20:24

2 Answers2

1

If you want to change or assign a value to gold element, take the gold map and assign the value for map key gold

goldMap := result["player"].(map[string]interface{})["inventory"].(map[string]interface{})
goldMap["gold"] = 100

But, Make sure your initial maps are not nil. Otherwise the binary will panic. To do that, you need to assign all the maps one by one and check whether nil or not

nipuna
  • 3,697
  • 11
  • 24
0

Map elements are not addressable; the map implementation is permitted to rearrange the elements in memory as needed, which would invalidate any pointers to those elements. Per the spec:

For an operand x of type T, the address operation &x generates a pointer of type *T to x. The operand must be addressable, that is, either a variable, pointer indirection, or slice indexing operation; or a field selector of an addressable struct operand; or an array indexing operation of an addressable array.

A map element is not among the list of addressable values.

You're better off defining struct(s) to match your data structure if at all possible; it will vastly simplify all usage of that data in your code. You can use json-to-go to frame out the data structure for you, though this should only be used to provide a working starting point.

Adrian
  • 42,911
  • 6
  • 107
  • 99