Sobes.tech
Middle+

Is it possible to take a pointer to a map element?

sobes.tech AI

Answer from AI

In Go, you cannot take a pointer to a map element directly because map elements do not have a stable memory address — they can move when the map changes. If you need to work with an element via a pointer, usually one of the following approaches is used:

  • Store pointers to values in the map, then you can get a pointer directly from the map.
  • Copy the value from the map into a separate variable and take a pointer to it.

Example with pointers in a map:

m := map[string]*int{}
val := 42
m["key"] = &val
fmt.Println(*m["key"]) // 42

Example with copying the value:

m := map[string]int{"key": 42}
val := m["key"]
ptr := &val
fmt.Println(*ptr) // 42

But changing through ptr will not affect the value in the map.