top | item 42946709

(no title)

eu | 1 year ago

it’s a good read, but i think it should focus more on some of the common mistakes that people make when slicing a slice.

discuss

order

rednafi|1 year ago

Slicing a slice is full of gotchas. I tend to forget all the rules and avoid it whenever I can.

adonovan|1 year ago

A slice operation s[i:] seems like it should be little more than an ADD instruction for a registerized slice where i is known to be in bounds, but a surprising little detail is that when i==cap(s) we really don't want to create an empty slice whose data pointer points one past the end of the original array, as this could keep some arbitrary object live. So the compiler generates a special branch-free sequence (NEG;SUB;ASR;AND) to compute the correct pointer increment, ((i - cap) >> 63) & (8 * i).

https://go.dev/play/p/J2U4djvMVoY

rendaw|1 year ago

Appending a slice is also full of gotchas. Sometimes it modifies the slice in place, sometimes it reallocates and copies.

bborud|1 year ago

It is a suprisingly hard thing to implement well. I have no idea how many times I have implemented slice-like things in C (back in the 1990-2000s when I mostly wrote C) and it was one of those things I never managed to be happy with.

fmbb|1 year ago

Can you link some article about these common mistakes? Sounds like good learnings can be had.