为什么append()修改提供的slice? (见例子) [英] Why does append() modify the provided slice? (See example)

查看:133
本文介绍了为什么append()修改提供的slice? (见例子)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您可以在Go Playground上运行示例代码



以下是代码:

 包主

导入fmt

func main(){
numbers:= [] int {1,2,3,4,5}

fmt.Println(numbers)
_ = append(numbers [0:1],numbers [2:] ...)
fmt.Println(numbers)
}
pre>

输出:

  [1 2 3 4 5] 



$ b $为什么数字通过append修改slice?这是预期的行为,如果是的话,你能向我解释为什么?我认为 append 不会修改它的参数。

解决方案

a href =http://blog.golang.org/go-slices-usage-and-internals =noreferrer> http://blog.golang.org/go-slices-usage-and-internals

如果附加到切片的内容不适合当前切片,则附加函数可以分配新的基础数组容量。追加不会修改底层数组。你必须重新分配变量的原因是,正如我在第一句中所说的那样,底层数组可以被重新分配,而旧的数据块仍然会指向旧数组。



请参阅此播放示例,以确切了解我在说什么。


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.

解决方案

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.

这篇关于为什么append()修改提供的slice? (见例子)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆