News for hackers. Stuff that matters.
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.

There are no comments on this comment yet.