Question about modifying struct in map

In Go i can modify struct in slice by index without copying. Why i can’t do that with map? Only solution is to store pointer in map.

Hi @asv1, can you share some code snippet that shows what you are trying to achieve?

Something like this maybe?

https://play.golang.org/p/Nl2XKScVpqV

It’s because map keys or values are not addressable, but slice indexes are. If you append to a slice, it doesn’t affect the other elements. If you add or remove an element to a map, the elements can be shuffled around in the backing memory. If you could take the address of an element and then modified the map, who knows what your pointer would point to any more; maybe the element associated with some other key, maybe some sentinel value to indicate that the slot is available, etc.

maps of pointers to structs have the same issue, but in that case, it’s just the pointers that get shuffled around when values are added and not the whole embedded structs.

1 Like

https://play.golang.org/p/Vk1gJUyxs-Q

1 Like

map keys or values are not addressable

if you take and save the address of one of its entries and afterwards put another bunch of entries into it, the saved address may be invalid. This is due to internal re-organization of hash tables when the load factor exceeds a certain threshold and the hash table needs to grow

1 Like

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