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.
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.
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!