Understanding Slice Capacity Changes: Dropping First vs. Last Items
In Go, slices are a data structure that provides a dynamically sized, mutable view of an underlying array. When the capacity of a slice changes, it affects the underlying array and memory management.
Consider the following Go code:
<code class="go">package main import "fmt" func main() { s := []int{2, 3, 5, 7, 11, 13} printSlice(s) // Drop its last two values s = s[:len(s)-2] printSlice(s) // Drop its first two values. s = s[2:] printSlice(s) } func printSlice(s []int) { fmt.Printf("len=%d cap=%d %v\n", len(s), cap(s), s) }</code>
Why does the capacity of the slice change when the first two items are dropped, but not when the last two are dropped?
To answer this question, we must understand how Go slices are implemented. They are a struct with three fields:
When the last two items of the slice are dropped (s = s[:len(s)-2]), the len field is decremented, but the array pointer and cap field remain the same. This is because the underlying array is not modified, and the slice still refers to the same array.
However, when the first two items of the slice are dropped (s = s[2:]), a new array is created to hold the new slice. The len field is decremented, the array pointer is updated to point to the new array, and the cap field is also decremented to reflect the smaller size of the new array.
Conclusion
The capacity of a slice changes when the first items are dropped because a new underlying array must be created to accommodate the slice. This is not necessary when the last items are dropped because the existing array can still be used.
The above is the detailed content of Why Does Dropping the First Elements of a Slice in Go Change its Capacity, But Dropping the Last Doesn\'t?. For more information, please follow other related articles on the PHP Chinese website!