phil535
(Philip Loibl)
September 17, 2017, 12:15pm
1
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
phil535
(Philip Loibl)
September 18, 2017, 10:57pm
3
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
system
(system)
Closed
December 18, 2017, 3:03pm
4
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.