在 golang 中,[:] 语法与数组赋值有何不同?
in golang what does the [:] syntax differ from the array assignment?
我目前正在阅读 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
检查上面 link 以了解 Slice 背后的内部结构
我目前正在阅读 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
检查上面 link 以了解 Slice 背后的内部结构