为什么append()会修改提供的切片?(参见示例)

huangapple go评论73阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2013年7月1日 06:01:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/17395261.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定