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.
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.
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
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.