Home > Article > Backend Development > Why Does Dropping Elements from the Beginning of a Go Slice Change Its Capacity?
Why does the capacity of a slice change when dropping the first n items?
In Go, slices are implemented as structures, resembling the following:
<code class="go">type slice struct { array unsafe.Pointer len int cap int }</code>
If we modify the function used to print the slice to include the pointer to the underlying array, we get the following output:
ptr=0x450000 len=6 cap=6 [2 3 5 7 11 13] ptr=0x450000 len=4 cap=6 [2 3 5 7] ptr=0x450008 len=2 cap=4 [5 7]
As you can see, dropping the last two items does not change the pointer, while dropping the first two items does. This is because a slice is essentially a window into the underlying array. Dropping items from the beginning forces the slice to be recreated in a new location with a different pointer, while dropping items from the end simply adjusts the length of the existing slice.
For further information, please refer to the following resources:
The above is the detailed content of Why Does Dropping Elements from the Beginning of a Go Slice Change Its Capacity?. For more information, please follow other related articles on the PHP Chinese website!