Resize slice len but the cap not resize

I want to ask a question. Is there func that the len of slice is not resized, but the cap is not resized. Because I don’t want reassign memory, it can cost .

for example ,
slice’ len = 5, slice cap = 10; after resize slice’ len = 0, slice’ cap = 10.

Hi. Just take out a new slice with zero items

In this example you see what the address of the array stays the same.

I’m pretty sure, this creates a “copy on write” slice either on the former filled slice or the later subsliced one.

Is properly defined which one is the one that gets reallocated in case of an append or is this UB?

Your code do make len = 0 and cap remain the same. But I am not sure if there is time cost and reallocation of memory. Wait for your answer.

It creates a new slice but that is just 12 bytes (on a 64-bit machine) but it reuses the underlying array.

1 Like

Maybe this clears it:

In the example a and b are two slices pointing to the same array, which is why appending to b is a visible change when printing a

Edit: I just now fully read the question about reallocation. From this other example it would seem there isn’t and internally just the len is modified: But Johan and Norbert mention there is, so I’ll have to take a better look.

Further edit: In this post it’s mentioned that Slicing does not copy the slice’s data. It creates a new slice value that points to the original array. But Effective Go mentions this: The length of a slice may be changed as long as it still fits within the limits of the underlying array; just assign it to a slice of itself. It seems to me the latter is the case we are dealing with.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.