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.

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

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么