Understanding Slice Capacity and Length in Go
When learning Go from its tutorial, one may encounter questions like:
Question:
In the code below, why are the slices c and d initialized with different values and capacities?
func main() { a := make([]int, 5) b := make([]int, 0, 5) c := b[:2] d := c[2:5] }
Answer:
In Go, slices are backed by arrays. When a slice is created with make, the backing array is initialized with its zero value. In this case, it's an array of integers, each initialized to 0.
When c is created as a slice of b, it shares the same backing array as b. Since b was created with a zero-length array, the first two elements of the backing array are 0. Thus, c has a length of 2 and its elements are both 0.
d is created as a slice of c starting at index 2. It also shares the same backing array as c. However, its capacity is different because it's a full slice expression. A full slice expression has a capacity equal to the difference between its first and last index, which in this case is 5 - 2 = 3.
Additional Resources:
The above is the detailed content of Why Do Go Slices `c` and `d` Have Different Values and Capacities After Slicing?. For more information, please follow other related articles on the PHP Chinese website!