Home > Article > Backend Development > Why does the slice capacity decrease when dropping the first two elements in Go Tour slide 11, but not when extending the slice length?
Understanding Slice Capacity Changes in the Go Tour #11
The Go Tour provides insightful demonstrations of the language's features, including slices. In slide 11, a slice of integers is manipulated to demonstrate its properties. However, one observation raises a question: why does the slice capacity change in the last line, while it remains unchanged in the previous operations?
Understanding the Effects of Slice Manipulation on Capacity
Slice capacity refers to the maximum number of elements the underlying array can hold before reallocation is required. The Go Tour code snippet performs the following operations:
Reasons for Capacity Reduction in the Last Line
Visualizing the Header Changes
The following code prints the slice header, which provides additional insights into the changes:
<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 shows that the header Data pointer moves from 272990208 to 272990216 when the first two elements are dropped, reducing the slice capacity.
The above is the detailed content of Why does the slice capacity decrease when dropping the first two elements in Go Tour slide 11, but not when extending the slice length?. For more information, please follow other related articles on the PHP Chinese website!