为什么一个数组的值可以被另一个变量改变?

huangapple go评论75阅读模式
英文:

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

问题

在Go语言中,数组是值类型。根据我的理解,值类型保存的是值,而不是内存地址。所以根据下面的代码,变量arr不应该被改变,但实际上它被改变了。我想知道为什么。

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

    arr[1] = 1

    fmt.Println(arr, arr2)
    // 输出 [0 1 0] [0 1 0]
    // 预期输出 [0 0 0] [0 1 0]
}

也许这是一个基础问题。但是我找到了一些文章,它们只是说了Go语言中的引用类型和值类型,但对于解决我的问题没有帮助。

英文:

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.

答案1

得分: -1

你正在使用的是切片,而不是数组。在你的程序中,arrarr2都是指向同一个数组的切片。将其修改为:

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

这样,arr就是一个数组,并且会按照你的期望工作。

英文:

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.

huangapple
  • 本文由 发表于 2021年12月6日 11:31:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/70240566.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定