Home  >  Article  >  Backend Development  >  golang: array sharing between slices

golang: array sharing between slices

WBOY
WBOYforward
2024-02-09 22:42:09848browse

golang: array sharing between slices

php editor Zimo will introduce you to the knowledge of array sharing between slices in golang in this article. In golang, a slice is a dynamic array that can be automatically expanded as needed. Array sharing between slices is a very important feature in golang. It allows multiple slices to share the same underlying array without copying data. This not only saves memory space but also improves performance. Next, we will explain in detail the principle and usage of array sharing between slices.

Question content

This explains the append function of slices.

As mentioned above, append returns the updated slice.

Does this mean that the newly created slice does not share the underlying array with the existing slice?

For other slicing operations, such as mySlice[x:y], the new slice will share the underlying array with mySlice, as shown below.

PS: Test code:

var names = make([]string, 4, 10)
names1 := append(names, "Tom")

So in this case there is enough free capacity in the name. Therefore append cannot create a new underlying array.

Output:

[   ]
[    Tom]

Shouldn't the output be the same as the shared underlying array?

I'm definitely missing something very basic here.

Workaround

You are right, names1 uses the same underlying array as names.

No, the output should not be the same because names has a length of 4 and names1 has a length of 5. Note that both have capacity (10).

Here's an example that might clarify this a bit:

func main() {
    emptyNames := make([]string, 0, 10)
    notEmptyNames := append(emptyNames, "Jerry")
    extendedNames := emptyNames[:1] // OK, because 1 < cap(emptyNames)
    fmt.Println("emptyNames:", emptyNames)
    //emptyNames: []
    fmt.Println("notEmptyNames:", notEmptyNames)
    //notEmptyNames: [Jerry]
    fmt.Println("extendedNames:", extendedNames)
    //extendedNames: [Jerry]
}

The above is the detailed content of golang: array sharing between slices. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete