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:
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:]...)
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:
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:]...)
}
Moving Items with Precision
With these helper functions, moving an item is straightforward:
func moveInt(array []int, srcIndex int, dstIndex int) []int {
value := array[srcIndex]
return insertInt(removeInt(array, srcIndex), value, dstIndex)
}
Sample Implementation and Output
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)
}
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.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3