duanpao4522 2013-06-30 22:01
浏览 10
已采纳

为什么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条回答 默认 最新

  • doujia2463 2013-06-30 22:14
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 simulink单相桥式整流电路
  • ¥35 问问51单片机流水灯的代码该怎么写
  • ¥15 关于#百度#的问题:感觉已经将字体段落、字体、页边距、纸张大小、文档网络调成与论文模板一致,为什么黄色部分字体左右的间距还是不一样啊,求私信发文件接收看一下
  • ¥15 stata webuse报错
  • ¥15 TypeError: Cannot read properties of undefined (reading 'status')
  • ¥15 如何利用AI去除图片中的竹架子
  • ¥15 python 写个基金爬取的代码,自动卖出功能
  • ¥15 Linux系统启动不起来
  • ¥15 为什么运行仿真数码管不亮(语言-c语言)
  • ¥15 陈仁良《直升机飞行动力学》小扰动线化方程如何推导