3 ms·
How does this work, in this code: var all []\*Item for _, item := range items { all = append(all, &item) } When &item is the same for al
by jupp0r 4y ago
How does this work,
in this code:
var all []\*Item
for _, item := range items {
all = append(all, &item)
}
When &item is the same for all iterations, that means that it's pointing to the same memory address. Is each item in items copied to this address prior to each iteration body invocation? This seems strange as this copy could potentially be very expensive. What am I missing?
- silisili 4y agoNothing, you got it. Most of the time you're iterating a slice of pointers, though, so only the address gets copied. And in those cases, this bug doesn't exist(unless of course you're going from * to ** for some reason).
- foldr 4y agoTo add to the sibling, you could iterate by index to avoid the copy: for i := range items { ptr := &items[i] ... } In this case of course you also get different semantics. The ptr variable is bound to the address of each of the original Item values in the slice, whereas in the code in your comment, &item is the address of a single heap-allocated Item variable.
- ytch 4y agoCould we assume it is like executing: var item Item item = items[0] all = append(all, &item) item = items[1] all = append(all, &item) ...
- skywhopper 4y agoYou aren’t missing anything. How expensive the copy is depends on the type of item. This is why you should probably use pointers in slices you’re going to loop over instead of the object itself.