Join GitHub today
GitHub is home to over 36 million developers working together to host and review code, manage projects, and build software together.Sign up
encoding/json: decoding into existing map pointer values unexpectedly reallocates them #31924
When decoding JSON data into an existing map object, an existing key's value is reallocated. I can't determine conclusively whether or not this is expected behavior, but the doc seems to be
The example below should explain this in a better way:
It is unexpected that B and A (as variables) lose coherence after the call to json.Unmarshal. The call reallocates "A.B", creating a copy of it. After that call, the objects are independent, which may be unexpected behavior.
What did you expect to see?
What did you see instead?
Possibly relevant godoc from encoding/json
Specifically, this part:
To me implies that it does not allocate a new value and set the pointer to point to it, but instead uses the existing value pointed at.
If a map is already present, we expect it to populate provided keys but not remove existing keys that weren't overwritten.
If a struct is already present, we sometimes expect it to populate provided keys but not zero out existing keys.
But if a map contains a struct (or pointer to a struct), it appears that the outcome is to replace the key entirely, rather than to populate recursively. Contrast with what you might expect for
And it sort of makes sense to me that, since map values aren't addressable, a map[string]struct would just replace the struct with a new struct, because trying to behave otherwise is actually pretty hard. But when it's a map[string]*struct, it's not insane to think it should act like populating a struct would normally.
Seems to be the samme with map[string]map[string]int, etc., which is to say, the recursion of decoding is not the same as you'd get by recursing yourself. If you have a map key-value pair