Home  >  Article  >  Backend Development  >  Why Does Shuffling a Slice Affect Another Slice Referencing the Same Underlying Array?

Why Does Shuffling a Slice Affect Another Slice Referencing the Same Underlying Array?

Susan Sarandon
Susan SarandonOriginal
2024-10-26 22:44:02251browse

Why Does Shuffling a Slice Affect Another Slice Referencing the Same Underlying Array?

Understanding Array Treatment in Go

The documentation at http://golang.org/doc/effective_go.html#arrays highlights the value-based nature of arrays in Go, where assigning an array to another creates a copy of all elements. This principle also applies to function arguments, where the function receives a copy of the array, not a pointer.

Based on this information, one would expect the following code to result in distinct arrays for arr2 and arr in the main() function:

<code class="go">package main

import (
    "fmt"
    "rand"
    "time"
)

func shuffle(arr []int) {
    rand.Seed(time.Nanoseconds())
    for i := len(arr) - 1; i > 0; i-- {
        j := rand.Intn(i)
        arr[i], arr[j] = arr[j], arr[i]
    }
}

func main() {
    arr := []int{1, 2, 3, 4, 5}
    arr2 := arr
    shuffle(arr)
    for _, i := range arr2 {
        fmt.Printf("%d ", i)
    }
}</code>

However, the code unexpectedly shuffles arr2 as well. This behavior stems from the fact that the provided code operates on slices, not arrays.

Slices: A Reference to Arrays

Go utilizes slices as a more flexible and efficient way to handle sequences of values. Slices are references to underlying arrays, and assigning one slice to another simply duplicates the reference.

In the example code, the arr := []int{1, 2, 3, 4, 5} line creates a slice that references an anonymous underlying array of integers. When arr2 := arr is executed, it creates a new slice that also references the same underlying array.

Implications for Array Treatment

Since arr and arr2 both reference the same underlying array, modifying arr in the shuffle() function also affects arr2. This behavior aligns with the principle of assigning one slice to another simply duplicating the reference, not creating a new copy of the underlying array.

Therefore, the code correctly shuffles both arr and arr2 because they both reference the same underlying array of integers.

The above is the detailed content of Why Does Shuffling a Slice Affect Another Slice Referencing the Same Underlying Array?. 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