Moving a slice element from one position to another in go

I am trying to move an element 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 leads to the following conclusion:

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 result to 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

+4
source share
1 answer

The problem is that newSliceit is not a separate copy slice- they refer to the same underlying array.

Therefore, when you assign newSlice, you modify the underlying array and therefore slicealso.

To fix 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 also added the variable val, not hardcoding 1, as the value to be inserted.)

+2

Source: https://habr.com/ru/post/1675629/


All Articles