Moving an slice item from one position to another in go

I had the same issue before and I solved as:

func insertInt(array []int, value int, index int) []int {
    return append(array[:index], append([]int{value}, array[index:]...)...)
}

func removeInt(array []int, index int) []int {
    return append(array[:index], array[index+1:]...)
}

func moveInt(array []int, srcIndex int, dstIndex int) []int {
    value := array[srcIndex]
    return insertInt(removeInt(array, srcIndex), value, dstIndex)
}


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

    fmt.Println("slice: ", slice)

    slice = insertInt(slice, 2, 5)  
    fmt.Println("slice: ", slice)

    slice = removeInt(slice, 5) 
    fmt.Println("slice: ", slice)

    slice = moveInt(slice, 1, 4) 
    fmt.Println("slice: ", slice)
}

https://play.golang.org/p/Sfu1VsySieS


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.)

Tags:

Go