Sobes.tech
Junior — Middle

Is it possible to get the address of a specific element stored in an associative table (Map)?

sobes.tech AI

Answer from AI

In Go, you cannot directly obtain the address of a specific element stored in a map. This is because map elements can move in memory when changes occur, and the compiler does not allow taking the address of a value via indexing to prevent errors.

For example, the following code will not compile:

m := map[string]int{"a": 1}
p := &m["a"] // compile error: cannot take the address of m["a"]

If you need to work with the address of a value, you can store pointers or structures in the map, and then take the address of those:

m := map[string]*int{"a": new(int)}
*m["a"] = 42

Alternatively, copy the value from the map into a variable and take the address of that variable.