我試圖將切片中的某個位置從一個位置移動到另一個位置。 Go Playground將切片項從一個位置移動到另一個位置
indexToRemove := 1
indexWhereToInsert := 4
slice := []int{0,1,2,3,4,5,6,7,8,9}
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)
這會產生下列輸出:
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]
但我希望的輸出是這樣的:
slice: [0 2 3 4 5 6 7 8 9]
newSlice: [0 2 3 4 1]
slice: [0 2 3 4 1 **5** 6 7 8 9]
哪裏是我的錯嗎?
切片是引用數組的對象(Flimzy的答案)。另外請記住,你實際上可以使用裸陣列,但與切片相比,它們相當笨拙。儘管如此,它們在某些情況下仍然有用。 – RayfenWindspear