In the world of Go, slices are a fundamental data structure. However, their capacity and length can sometimes be confusing for beginners. Let's delve into the concepts using a practical 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 }
Understanding Slice Initialization
Both a and b are initialized using make, but with different parameters. a initializes an array of integers with a length of 5 and a capacity of 5, while b initializes an empty array with a capacity of 5.
Zero Values and Array Initialization
Go's concept of uninitialized variables is important here. When you create a variable without explicitly setting its value, it will be initialized with its zero value. For an integer array, this means an array containing all zeros.
Slicing and Zero Values
When you slice b with [:2], you create a new slice c. This slice points to the same backing array as b, but only the first two elements. Since the backing array was initialized with zeros, c will contain the elements [0,0].
Slicing and Capacity
Finally, when you slice c with [2:5], you create a new slice d. This slice shares the same backing array as c, but with different indices. The capacity of d is 5-2 = 3, because it represents the remaining elements in the backing array after slicing.
The above is the detailed content of What's the Difference Between Length and Capacity in Go Slices?. For more information, please follow other related articles on the PHP Chinese website!