Home > Backend Development > Golang > Why does modifying an array inside a function in Go also change a variable assigned to the same array outside the function?

Why does modifying an array inside a function in Go also change a variable assigned to the same array outside the function?

Susan Sarandon
Release: 2024-10-26 01:25:28
Original
799 people have browsed it

Why does modifying an array inside a function in Go also change a variable assigned to the same array outside the function?

Treatment of Arrays in Go

In Go, arrays are values, not references. Therefore, assigning one array to another will copy all the elements. Additionally, passing an array to a function will provide a copy, not a pointer.

Example Code Explanation

Consider the following code example:

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)
    }
}
Copy after login

In this code, the shuffle function takes an array as an input and shuffles its elements. However, even though we assign the original array to a new variable arr2 before calling shuffle, changes made to arr within the function are reflected in arr2.

Slices vs. Arrays

Go distinguishes between slices and arrays. While arrays are fixed-length lists of values, slices are references to underlying arrays. In the code example, both arr and arr2 refer to the same underlying array. As a result, any modifications made to arr are also applied to arr2. To create a distinct copy of an array, the slice must be allocated using make:

arr := []int{1, 2, 3, 4, 5}
arr2 := make([]int, len(arr))
copy(arr2, arr)
Copy after login

In this updated version, arr2 is no longer a reference to the original array, so modifications made to arr will not affect arr2.

The above is the detailed content of Why does modifying an array inside a function in Go also change a variable assigned to the same array outside the function?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template