|
|
|
|
|
by zeeboo
1883 days ago
|
|
I think I didn't communicate my point clearly. Consider this hypothetical program: x := make(map[int]int)
x[0] = 5
y := &x[0]
*y = 10
print(x[0]) // 5 or 10?
x[0] = 6
print(*y) // 6 or 10?
// force the map to grow and reallocate the buckets
for j := 1; j < 100; j++ {
x[j] = j
}
*y = 11
print(x[0]) // 5, 6, 10, or 11?
The crux of the problem is answering what y actually points at: the value in the map bucket, or some freshly allocated value? There are problems with whichever one you pick.edit: changed the second print to *y instead of x[0]. thanks
masklinn for catching this error. |
|
Do you mean `print(*y)`? You just assigned to `x[0]` so its value should not be in question.
Also
> if it's the latter, resizing the map invalidates the pointer, so it must be updated somehow.
It doesn't (have to) invalidate the pointer though. When resized the map's content get copied to a new backing buffer, the pointer can keep pointing to the old buffer. That's basically the same behaviour as slices: when a slice resizes, a new backing array is allocated, the contents get copied to the new array, and the slice is retargeted to the new array. There can be other slices pointing to the old array (it's of course a very bad idea to update slices to shared arrays, but Go will let you do it).