Go Slices: Demystifying Capacity and Length
In Go, slices are a powerful data structure for working with collections of data. Two important concepts related to slices are capacity and length, which can be confusing to understand at first.
Consider the following example:
func main() { a := make([]int, 5) // [0,0,0,0,0] len=5 cap=5 b := make([]int, 0, 5) // [] len=0 cap=5 c := b[:2] // [0,0] len=2 cap=5 d := c[2:5] // [0,0,0] len=3 cap=3 }
Capacity vs. Length
In this example, a has a length of 5 (the number of elements it contains) and a capacity of 5 (the number of elements it can hold before reallocation). b has a length of 0 and a capacity of 5, indicating that it initially contains no elements but has the potential to grow to hold up to 5 elements.
Zeroed Elements
When you create a slice with make([]int, 0, 5) as in b, a backing array is created and initialized with the zero value for its elements. This means that even though b initially has no elements, its backing array contains five zeroed values.
When you slice a slice, you are creating a new slice that shares the same backing array. Therefore, when you assign c := b[:2], you create a new slice that references the first two zeroed elements of the backing array. Hence, c has a length of 2 and contains the values [0,0].
Capacity of Sliced Slices
When you slice a slice, the capacity of the resulting slice is determined by the difference between the last index of the slice expression and the first index. In the case of d := c[2:5], this difference is 3 (5 - 2). Therefore, d has a capacity of 3.
Conclusion
Understanding capacity and length is crucial for working effectively with slices in Go. Remember that slices always reference a backing array, and the capacity represents the size of this backing array. By slicing slices, you create new slices that share the same backing array and inherit its properties, including its capacity.
The above is the detailed content of Go Slices: What's the Difference Between Capacity and Length?. For more information, please follow other related articles on the PHP Chinese website!