Home  >  Article  >  Backend Development  >  Are Go Slices and Arrays Treated the Same When Assigned and Passed?

Are Go Slices and Arrays Treated the Same When Assigned and Passed?

DDD
DDDOriginal
2024-10-26 01:23:27269browse

 Are Go Slices and Arrays Treated the Same When Assigned and Passed?

Treatment of Slices vs. Arrays in Go

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

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

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.

Code Example

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.

Conclusion

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!

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