Home >Backend Development >Golang >How Does Re-slicing Behave with Underlying Arrays in Go Slices?

How Does Re-slicing Behave with Underlying Arrays in Go Slices?

Susan Sarandon
Susan SarandonOriginal
2024-12-26 19:02:10508browse

How Does Re-slicing Behave with Underlying Arrays in Go Slices?

Re-slicing Slices in Go: Confusion and Clarity

In Go, slices are a powerful and efficient way to represent arrays of data. However, understanding their intricacies can be challenging for beginners. One such aspect is the concept of re-slicing slices.

Consider the following code:

package main

import "fmt"

func main() {
    a := make([]int, 5)
    printSlice("a", a)
    b := make([]int, 0, 5)
    printSlice("b", b)
    c := b[:2]
    printSlice("c", c)
    d := c[2:5]
    printSlice("d", d)
}

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

The program creates four slices: a, b, c, and d. The surprising result is that slice c, created as a slice of the first two elements of b, has a capacity of 5 instead of 2.

To understand this behavior, we need to delve into the concept of underlying arrays. In Go, slices do not store the actual data; rather, they reference an underlying array. When a slice is created, it points to a segment of this underlying array.

In the above example, when b is created with a length of 0 but a capacity of 5, it reserves 5 slots in an underlying array. When slice c is created from b, it becomes a window over the first two elements of b. However, the underlying array and thus the capacity of c remains 5, which includes the unused slots in b.

This concept of re-slicing is further illustrated by modifying the code slightly:

func main() {
    b := make([]int, 0, 5)
    c := b[:2]
    d := c[1:5] // this is equivalent to d := b[1:5]
    d[0] = 1
    printSlice("c", c)
    printSlice("d", d)
}

In this case, modifying the value of d also modifies the value of c, demonstrating that c and d are just different windows over the same underlying array.

Understanding the concept of re-slicing is crucial for effectively working with slices in Go. It allows you to create slices that dynamically adjust to different data sizes without the need for copying or reallocating memory.

The above is the detailed content of How Does Re-slicing Behave with Underlying Arrays in Go Slices?. 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