Home  >  Article  >  Backend Development  >  How Does Dropping Elements from a Go Slice Affect Its Capacity?

How Does Dropping Elements from a Go Slice Affect Its Capacity?

Linda Hamilton
Linda HamiltonOriginal
2024-11-01 09:00:30597browse

How Does Dropping Elements from a Go Slice Affect Its Capacity?

Capacity of Slices After Dropping Items

When working with slices in Go, it's important to understand how their capacity changes based on the type of modification made. To illustrate this, let's examine a code snippet and its output:

package main

import "fmt"

func main() {
    s := []int{2, 3, 5, 7, 11, 13}
    printSlice(s)

    // Drop its last two values
    s = s[:len(s)-2]
    printSlice(s)

    // Drop its first two values.
    s = s[2:]
    printSlice(s)
}

func printSlice(s []int) {
    fmt.Printf("len=%d cap=%d %v\n", len(s), cap(s), s)
}

Output:

len=6 cap=6 [2 3 5 7 11 13]
len=4 cap=6 [2 3 5 7]
len=2 cap=4 [5 7]

Why Different Capacities After Dropping Items?

Notice that when we drop the last two items from the slice (s = s[:len(s)-2]), the capacity remains unchanged at 6, while dropping the first two items (s = s[2:]) reduces the capacity to 4.

The reason for this difference lies in how slices are implemented in Go. Slices are essentially a view into an underlying array. Dropping the last two values adjusts the slice's length, which is the number of elements the slice points to, but it does not affect the capacity, which is the size of the underlying array.

However, dropping the first two values results in a new underlying array being created to hold the reduced slice. This is because the elements in the original underlying array are shifted down two places to fill the gap, and a new array is necessary to accommodate the shifted elements.

The above is the detailed content of How Does Dropping Elements from a Go Slice Affect Its Capacity?. 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