英文:
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
你正在使用的是切片,而不是数组。在你的程序中,arr
和arr2
都是指向同一个数组的切片。将其修改为:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论