Home > Article > Backend Development > How do you move a slice item in Go without creating duplicates?
Traversing slices in Go often involves rearranging their elements. Attempting to directly move an item from one position to another might lead to unexpected results, as demonstrated in the provided code snippet:
<code class="go">slice := []int{0,1,2,3,4,5,6,7,8,9} indexToRemove := 1 indexWhereToInsert := 4 slice = append(slice[:indexToRemove], slice[indexToRemove+1:]...) newSlice := append(slice[:indexWhereToInsert], 1) slice = append(newSlice, slice[indexWhereToInsert:]...)</code>
This approach intends to shift the item at indexToRemove to indexWhereToInsert, but the output exhibits two copies of the moved item. The error lies in the way the item is removed and inserted. Let's explore an alternative approach:
Utilizing Custom Functions for Item Manipulation
Instead of manually modifying the slice, we can create dedicated functions for insertion and removal:
<code class="go">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:]...) }</code>
Moving Items with Precision
With these helper functions, moving an item is straightforward:
<code class="go">func moveInt(array []int, srcIndex int, dstIndex int) []int { value := array[srcIndex] return insertInt(removeInt(array, srcIndex), value, dstIndex) }</code>
Sample Implementation and Output
<code class="go">func main() { slice := []int{0,1,2,3,4,5,6,7,8,9} fmt.Println("Original slice:", slice) slice = insertInt(slice, 2, 5) fmt.Println("After insertion:", slice) slice = removeInt(slice, 5) fmt.Println("After removal:", slice) slice = moveInt(slice, 1, 4) fmt.Println("After moving:", slice) }</code>
Output:
Original slice: [0 1 2 3 4 5 6 7 8 9] After insertion: [0 1 2 3 4 2 5 6 7 8 9] After removal: [0 1 2 3 4 5 6 7 8 9] After moving: [0 2 1 3 4 5 6 7 8 9]
This approach correctly shifts the item at index 1 to index 4, resulting in the expected output.
The above is the detailed content of How do you move a slice item in Go without creating duplicates?. For more information, please follow other related articles on the PHP Chinese website!