duanhe2027 2017-04-25 16:52
浏览 60
已采纳

将切片项目从一个位置移动到另一个位置

I' trying to move an item from one position to another inside a slice. Go Playground

indexToRemove := 1
indexWhereToInsert := 4

slice := []int{0,1,2,3,4,5,6,7,8,9}    

slice = append(slice[:indexToRemove], slice[indexToRemove+1:]...)
fmt.Println("slice:", slice)    

newSlice := append(slice[:indexWhereToInsert], 1)
fmt.Println("newSlice:", newSlice)

slice = append(newSlice, slice[indexWhereToInsert:]...)
fmt.Println("slice:", slice)

This produces to following output:

slice: [0 2 3 4 5 6 7 8 9]
newSlice: [0 2 3 4 1]
slice: [0 2 3 4 1 1 6 7 8 9] 

But I would expect the output be like this:

slice: [0 2 3 4 5 6 7 8 9]
newSlice: [0 2 3 4 1]
slice: [0 2 3 4 1 **5** 6 7 8 9] 

Where is my fault?

  • 写回答

1条回答 默认 最新

  • doutenglou6588 2017-04-25 17:07
    关注

    The problem is that newSlice is not a distinct copy of slice--they reference the same underlying array.

    So when you assign to newSlice, you're modifying the underlying array, and thus slice, too.

    To remedy this, you need to make an explicit copy:

    Playground

    package main
    
    import (
        "fmt"
    )
    
    func main() {
    
        indexToRemove := 1
        indexWhereToInsert := 4
    
        slice := []int{0,1,2,3,4,5,6,7,8,9}
    
        val := slice[indexToRemove]
    
        slice = append(slice[:indexToRemove], slice[indexToRemove+1:]...)
        fmt.Println("slice:", slice)    
    
        newSlice := make([]int, indexWhereToInsert+1)
        copy(newSlice,slice[:indexWhereToInsert])
        newSlice[indexWhereToInsert]=val
        fmt.Println("newSlice:", newSlice)
        fmt.Println("slice:", slice)
    
        slice = append(newSlice, slice[indexWhereToInsert:]...)
        fmt.Println("slice:", slice)    
    }
    

    (Note that I've also added the val variable, rather than hardcoding 1 as the value to be inserted.)

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

报告相同问题?

悬赏问题

  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作