Home >Backend Development >Golang >Why Does Dropping Slice Elements at the Beginning Reduce Capacity?
A Tour of Go demonstrates the behavior of slices, where a slice of integers is initialized and modified through a series of operations. One puzzling observation in the demonstration is the reduction in slice capacity after dropping the first two elements in the last line.
Slices are backed by an array, and dropping elements at the beginning of a slice effectively moves the start point of the slice within the array. This reduces the number of elements between the slice start and array end, resulting in a smaller capacity.
Dropping elements at the end of the slice does not affect its capacity because it does not alter the distance between the slice start and array end. The slice still occupies the same range of slots within the backing array.
It's important to note that these operations modify the slice itself, not the backing array. The array remains unchanged throughout the process.
By printing the slice header, we can observe the changes more clearly:
<code class="go">func printSlice(s []int) { sh := (*reflect.SliceHeader)(unsafe.Pointer(&s)) fmt.Printf("header=%+v len=%d cap=%d %v\n", sh, len(s), cap(s), s) }</code>
The output demonstrates how the data pointer moves when elements are dropped from the beginning or end of the slice:
header=&{Data:272990208 Len:6 Cap:6} len=6 cap=6 [2 3 5 7 11 13] header=&{Data:272990208 Len:0 Cap:6} len=0 cap=6 [] header=&{Data:272990208 Len:4 Cap:6} len=4 cap=6 [2 3 5 7] header=&{Data:272990216 Len:2 Cap:4} len=2 cap=4 [5 7]
The above is the detailed content of Why Does Dropping Slice Elements at the Beginning Reduce Capacity?. For more information, please follow other related articles on the PHP Chinese website!