A Tale of Two Copies
storj.io6 pointsby zeeboo0 comments
x := make([]int, 5)
y := &x[0]
x[3] = 8
*y = 5
print(x[0]) // always prints 5
as compared to x := make(map[int]int)
y = &x[0] // btw, is this even valid? let's assume it implicitly does x[0] = 0
x[3] = 8
*y = 5
print(x[0]) // maybe sometimes prints 5?
is meaningfully different. For slices, we know that x[0] will always print 5 until the value of x is reassigned in some way. 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.