Re:a[low:high:max] in Golang – A Rare Slice Trick
by mook on Saturday March 18, 2023 @03:44PM
(#35212423)
Yes-ish; because go has no immutable slices, it's just copy-on-realloc. Which is if course obvious if realize that's what it's actually doing…
Re:a[low:high:max] in Golang – A Rare Slice Trick
by masklinn on Sunday March 19, 2023 @03:16AM
(#35216768)
> Sounds like they're just badly describing copy-on-write.
It’s not quite copy-on-write, and what it’s really describing is a workaround / safeguard.
The problem is that by default Go slices will have as large a capacity as they can based on the parent, this is a problem if you return a slice to a still-in-use slice or array, and the caller decides to use that slice as a vector (either because the contract is not well documented or because they fucked up): appending to the “borrow” will happily go and stomp over the backing array, which may be holding in-use data of an other slice or the original array.
By forcing the slice to have no extra capacity, if a caller tries to append it’ll force a “fork” by realloc-ing and avoid the issue.
The original slice uses no extra memory because as long as you treat it as immutable it won't actually make a copy. As soon as you try to modify it, then the copy is made and the extra memory used.