4 ms·
Here's a succinct demonstration: https://go.dev/play/p/Li6_Rpe2R5L https://go.dev/play/p/Li6_Rpe2R5L Basically: a slice is a triple of {ptr to allocation, numb
by chrsig 4y ago
Here's a succinct demonstration: https://go.dev/play/p/Li6_Rpe2R5L https://go.dev/play/p/Li6_Rpe2R5L
Basically:
a slice is a triple of {ptr to allocation, number of elements used, size of allocation}
the slices will share the same underlying allocation. By specifying the third parameter in the slice function, you set the capacity equal to the number of elements in your slice. This forces the next append to reallocate and copy the contents into a new region.
Without bounding the capacity when creating a new slice, the append operation could possibly continue using the same allocation, shared with the original slice. It could possibly resize and copy as well. It depends on how full the slice is, and is an implementation detail subject to change between versions.
- ErikCorry 4y agoHere another illustration of how slices sometimes alias each other, sometimes not. https://mobile.twitter.com/erikcorry/status/1561635841495236610 https://mobile.twitter.com/erikcorry/status/1561635841495236...
- secondraft 4y agoand yet another one (thanks to Erik): https://github.com/tlk/go-wat/blob/41cc21294a953dc7ad07a9b40a2486acf816b8e1/main.go#L27 https://github.com/tlk/go-wat/blob/41cc21294a953dc7ad07a9b40...