在 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:]...)
此方法旨在將 indexToRemove 處的項目移至 indexWhereToInsert,但輸出顯示移動項目的兩個副本。錯誤在於刪除和插入項目的方式。讓我們探索另一種方法:
利用自訂函數進行專案操作
我們可以建立用於插入和刪除的專用函數,而不是手動修改切片:
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("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)
}
輸出:
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]
此方法正確地將索引 1 處的項目移至索引 4,從而產生預期的輸出。
免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。
Copyright© 2022 湘ICP备2022001581号-3