dsfsdfsd34324 2019-01-01 01:57
浏览 45
已采纳

重新分配slice参数的行为有所不同

package main

import "fmt"

func main() {
    paths := []string{"hello", "world", "mars"}
    var result = delete(paths, 1)
    fmt.Println(result)
    fmt.Println(paths)
}

func delete(paths []string, index int) []string {
    paths = append(paths[:index], paths[index+1:]...)
    return paths
}

The result of the code above is the following:

[hello mars]

[hello mars mars]

As you see, the second fmt.Println(paths) obviously uses the modified slice but does not use the reassigned value. Why is that? I was expecting it to print [hello mars] like in the print before.

I know that paths being passed is not the same slice as paths parameter in the delete() function expect for referencing the same underlying array. But I still don't understand how I changed the underlying array of the paths being passed to delete function as it prints [hello mars mars] instead of [hello world mars].

  • 写回答

1条回答 默认 最新

  • duanhuang7591 2019-01-01 02:22
    关注

    Because, as you said, the same underlying array is in use. When you do the append, paths[:1] is a slice of length 1 and capacity 3, and paths[2:] is a slice of length 1, so there is enough room in the underlying array of the first slice to append the new value without allocating a new array. paths in main is still a slice of length 3 since it was never modified, but since the underlying array was modified (specifically element 1), you see the value that you see.

    You may want to take a look at https://blog.golang.org/go-slices-usage-and-internals if you haven't already.

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

报告相同问题?

悬赏问题

  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 单片机无法进入HAL_TIM_PWM_PulseFinishedCallback回调函数
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch