Home > Backend Development > Golang > Why Do Go Slices `c` and `d` Have Different Values and Capacities After Slicing?

Why Do Go Slices `c` and `d` Have Different Values and Capacities After Slicing?

Mary-Kate Olsen
Release: 2024-12-21 02:35:10
Original
236 people have browsed it

Why Do Go Slices `c` and `d` Have Different Values and Capacities After Slicing?

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]
}
Copy after login

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:

  • [Go Slices: Usage and Internals](https://blog.golang.org/slices)
  • [Arrays, Slices (and Strings): The Mechanics of 'append'](https://blog.golang.org/slices-appending)

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template