Home >Backend Development >Golang >Go Slices: Why Do Slices c and d Have Their Respective Lengths and Capacities?

Go Slices: Why Do Slices c and d Have Their Respective Lengths and Capacities?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-28 20:23:13719browse

Go Slices: Why Do Slices c and d Have Their Respective Lengths and Capacities?

Go Slices: Understanding Capacity and Length

When working with slices in Go, it's crucial to understand the concepts of capacity and length. These properties play a significant role in slice operations and affect the behavior of slices when sliced or appended.

Consider the following code 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
}

This code raises various questions regarding the length and capacity of slices c and d:

  • Why does c have a length of 2 and contain [0,0]?

    Although b was initially empty ([], length=0), it's important to note that Go arrays and slices are always initialized with their zero values. In the case of integers, the zero value is 0. Therefore, when you slice b with [:2], you create a new slice that inherits the zeroed values of b.

  • Why does d have a capacity of 3?

    When you slice a slice in Go, it reuses the same underlying array. In this case, d shares the same backing array as c. The capacity of d is calculated as end-start, where start and end are the start and end indices of the slice expression ([2:5]), respectively. Therefore, d's capacity is 5 (end) - 2 (start) = 3.

The above is the detailed content of Go Slices: Why Do Slices c and d Have Their Respective Lengths and Capacities?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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