英文:
Why does append() modify the provided slice? (See example)
问题
你可以在Go Playground上运行示例代码。
这是代码:
package main
import "fmt"
func main() {
numbers := []int{1, 2, 3, 4, 5}
fmt.Println(numbers)
_ = append(numbers[0:1], numbers[2:]...)
fmt.Println(numbers)
}
输出结果:
[1 2 3 4 5]
[1 3 4 5 5]
为什么numbers
切片会被append
修改?这是预期的行为吗?如果是,你能解释一下为什么吗?我以为append
不会修改它的参数。
英文:
You can run the example code on Go Playground.
Here is the code:
package main
import "fmt"
func main() {
numbers := []int{1, 2, 3, 4, 5}
fmt.Println(numbers)
_ = append(numbers[0:1], numbers[2:]...)
fmt.Println(numbers)
}
Output:
[1 2 3 4 5]
[1 3 4 5 5]
Why was the numbers
slice modified by append? Is this expected behavior and if yes, could you explain to me why? I thought append
doesn't modify its arguments.
答案1
得分: 21
请参阅http://blog.golang.org/go-slices-usage-and-internals。
如果您要附加到切片的内容不适合当前切片的容量,append函数可能会分配一个新的基础数组。append 会修改基础数组。您必须将其重新分配给变量的原因是,正如我在第一句中所说,基础数组可能会被重新分配,而旧的切片仍将指向旧的数组。
请参阅此播放示例以了解我所说的确切内容。
英文:
See http://blog.golang.org/go-slices-usage-and-internals.
The append function could allocate a new underlying array if what you are appending to the slice does not fit in the current slice's capacity. Append does modify the underlying array. The reason you have to assign back to the variable is because, as I said in the first sentence, the underlying array could be reallocated and the old slice will still point to the old array.
See this play example to see exactly what I am talking about.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论