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

Time:12-07

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.

CodePudding user response:

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.

  •  Tags:  
  • go
  • Related