Convert map[int]T to map[int]*T [SOLVED]

Hello,

I’d like to convert a map of structs to a map of struct pointers (example: https://play.golang.org/p/XAaT7Iti4z).

Why does the first implementation not work?

Is there an easier way to do this if i do not need the original map anymore?

Best Regards,
phil535

This part of the code…

for k, v := range m1 {
	m2[k] = &v
}

…behaves as follows:

  • In each iteration, v receives a copy of m1[k].
  • In each iteration, m2[k] receives a pointer to v.

v is always the same variable inside the loop; it only gets different values assigned in each iteration.
After the loop, all elements of m2 point to v, and v contains 1. This is why the unexpected result occurs.

The second option does it right by assigning a pointer to the real element instead of v.

2 Likes

Thanks for your answer and the explanation.

I’m using the gopkg.in/yaml.v2 package and thought it is not able to parse into *T types, but I was wrong.

My issue is solved now by using map[int]*T from scratch.

Best Regards,
Philip

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.