我试图将一个项目从一个位置移动到一个切片内的另一个位置。去游乐场
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)
Run Code Online (Sandbox Code Playgroud)
这会产生以下输出:
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]
Run Code Online (Sandbox Code Playgroud)
但我希望输出是这样的:
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]
Run Code Online (Sandbox Code Playgroud)
我的错在哪里?
我之前遇到过同样的问题,我解决了:
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("slice: ", slice)
slice = insertInt(slice, 2, 5)
fmt.Println("slice: ", slice)
slice = removeInt(slice, 5)
fmt.Println("slice: ", slice)
slice = moveInt(slice, 1, 4)
fmt.Println("slice: ", slice)
}
Run Code Online (Sandbox Code Playgroud)
https://play.golang.org/p/Sfu1VsySieS
问题是这newSlice不是不同的副本slice——它们引用相同的底层数组。
因此,当您分配给 时newSlice,您正在修改底层数组,因此slice也修改了 。
为了解决这个问题,您需要制作一个显式副本:
package main
import (
"fmt"
)
func main() {
indexToRemove := 1
indexWhereToInsert := 4
slice := []int{0,1,2,3,4,5,6,7,8,9}
val := slice[indexToRemove]
slice = append(slice[:indexToRemove], slice[indexToRemove+1:]...)
fmt.Println("slice:", slice)
newSlice := make([]int, indexWhereToInsert+1)
copy(newSlice,slice[:indexWhereToInsert])
newSlice[indexWhereToInsert]=val
fmt.Println("newSlice:", newSlice)
fmt.Println("slice:", slice)
slice = append(newSlice, slice[indexWhereToInsert:]...)
fmt.Println("slice:", slice)
}
Run Code Online (Sandbox Code Playgroud)
(请注意,我还添加了val变量,而不是硬编码1为要插入的值。)