Sobes.tech
Senior

Is it possible to take a pointer to a value stored in a map?

sobes.tech AI

Answer from AI

In Go, you cannot directly take a pointer to a value stored in a map if that value is not addressable. When accessing an element of a map, for example m[key], a copy of the value is returned, not a reference to it.

However, if the map stores pointers, you can work with them:

m := map[string]*int{}
val := 42
m["key"] = &val
ptr := m["key"] // ptr has type *int

If the map stores values (not pointers), you cannot directly take the address of an element:

m := map[string]int{"key": 42}
// ptr := &m["key"] // compilation error: cannot take the address of m["key"]

To modify a value in the map through a pointer, you can:

  • Store pointers to values in the map.
  • Retrieve the value, modify it, and write it back to the map.

Example:

m := map[string]int{"key": 42}
val := m["key"]
val = 100
m["key"] = val

In summary: you cannot take a pointer to a value in a map directly unless it is a pointer. You need to either store pointers or work with copies and update the map.