我目前正在阅读 GoLang 教程并有以下疑问。
arr1:=[...]int{1,2,3}
arr2:=arr1
arr1[1]=99
fmt.Println(arr1)
fmt.Println(arr2)
它输出以下语句
[1 99 3]
[1 2 3]
here only array a is modified, which makes sense as an array is treated as values.
如果我尝试跟随事情变得困惑
a:=[...]int{1,2,3}
b:=a[:]
a[1]=88
fmt.Println(a)
fmt.Println(b)
这会导致打印
[1 88 3]
[1 88 3]
问题:这是否意味着说 b:=a
创建了数组的副本,说 b:=a[:]
将创建一个指向底层数组(本例中为“a”)?
最佳答案
Slicing does not copy the slice's data. It creates a new slice value that points to the original array. This makes slice operations as efficient as manipulating array indices. Therefore, modifying the elements (not the slice itself) of a re-slice modifies the elements of the original slice
https://blog.golang.org/slices-intro
检查上面的链接以了解 Slice 背后的内部结构
关于arrays - 在 golang 中 [:] syntax differ from the array assignment?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66720994/