Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

why the value of an array could be changed by another variable

the array in golang is value type. In my understanding, value type save the value, but not a memory address. So the following code, variable arr shouldn’t be changed. but it no. I want know why

func main() {
    arr := []int{0,0,0}
    arr2 := arr

    arr[1] = 1

    fmt.Println(arr, arr2)
    // output [0 1 0] [0 1 0]
    // output in thought [0 0 0] [0 1 0]
}

maybe this is a basic question. But I found some article. they all just said which are reference types and value types in golang. But it couldn’t help me to solve my problem.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You are using a slice, not an array. In your program, both arr and arr2 are slices pointing to the same array. Change it so that:

    arr := [3]int{0,0,0}

Then, arr is an array, and it works as you expect.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading