arrays - 在 golang 中 [:] syntax differ from the array assignment?

标签 arrays go 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

检查上面的链接以了解 Slice 背后的内部结构

关于arrays - 在 golang 中 [:] syntax differ from the array assignment?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66720994/

相关文章:

c++ - 数组作为函数参数 - 编译错误

javascript - 如何在同时支持window和linux的javascript数组下转义 ':'、 ","和 '()'?

http - 有没有一种方法可以检查HTTP请求中的无效查询参数?

python - 将 Python 中的字符串拆分为长度恒定但右对齐的 block

go - 如何使用在golang中通过引用传递的索引访问 slice 中的元素

arrays - 在Fortran中访问返回数组的元素

arrays - 根据另一个值返回PowerShell数组值

docker - 从另一个容器访问Neo4J

go - 使用 Go 删除​​链接列表中的项目

Java 3D数组: Storing cube,检索立方体切片