In Go, slices and arrays have distinct behaviors despite their similarities. This distinction affects how they are treated when assigned and passed as arguments.
Arrays are fixed-size collections of elements, with each element occupying a specific index. Assigning one array to another results in a copy of all elements, regardless of their size. This means that any modifications made to an assigned array will not affect the original array.
Slices, on the other hand, are flexible, dynamic references to an underlying array. When you assign a slice to another variable, you are creating a reference to the same underlying array, not a copy. Modifications made to either slice will affect the underlying array and, therefore, both references.
Consider the following Go code:
<code class="go">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>
In this example, the intention is to shuffle the arr2 slice while leaving arr intact. However, due to the way slices work, both arr and arr2 reference the same underlying array. Consequently, when shuffle() exchanges elements within arr, the changes are also reflected in arr2.
The result is "1 5 2 4 3," indicating the shuffling of arr and arr2. This behavior arises from the distinction between slices (which are references) and arrays (which are fixed-size collections). When working with arrays in Go, it's important to be aware of this fundamental difference.
The above is the detailed content of Are Go Slices and Arrays Treated the Same When Assigned and Passed?. For more information, please follow other related articles on the PHP Chinese website!