我试图将切片中的某个位置从一个位置移动到另一个位置。 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