Home > Article > Backend Development > How to Move an Item Within a Slice in Go Without Duplication?
Moving an Item Within a Slice in Go
In Go, it is common to manipulate slices, which are dynamic data structures that hold a sequence of elements. One task that you may encounter is moving an item from one position to another within the slice.
To address this, you may attempt the following approach:
slice := []int{0,1,2,3,4,5,6,7,8,9} indexToRemove := 1 indexWhereToInsert := 4 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)
However, this approach results in unexpected behavior:
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]
As you noticed, the item in the original position is duplicated when inserted.
Solution:
To correctly move an item within a slice, you can use the following approach:
Remove the Item from its Original Position:
removeItem := slice[indexToRemove] updatedSlice := append(slice[:indexToRemove], slice[indexToRemove+1:]...) fmt.Println("Updated slice before moving:", updatedSlice)
Insert the Item at the New Position:
insertedSlice := append(updatedSlice[:indexWhereToInsert], removeItem) finalSlice := append(insertedSlice, updatedSlice[indexWhereToInsert:]...) fmt.Println("Final slice after moving:", finalSlice)
Here's a working code example:
func main() { slice := []int{0,1,2,3,4,5,6,7,8,9} indexToRemove := 1 indexWhereToInsert := 4 removeItem := slice[indexToRemove] updatedSlice := append(slice[:indexToRemove], slice[indexToRemove+1:]...) fmt.Println("Updated slice before moving:", updatedSlice) insertedSlice := append(updatedSlice[:indexWhereToInsert], removeItem) finalSlice := append(insertedSlice, updatedSlice[indexWhereToInsert:]...) fmt.Println("Final slice after moving:", finalSlice) }
Output:
Updated slice before moving: [0 2 3 4 5 6 7 8 9] Final slice after moving: [0 2 3 4 1 5 6 7 8 9]
The above is the detailed content of How to Move an Item Within a Slice in Go Without Duplication?. For more information, please follow other related articles on the PHP Chinese website!