func PopSliceElementByIndex(slice []int, index int) (res []int) {
res = append(slice[:index], slice[index+1:]...)
return
}
func PopSliceElementByIndex2(slice []int, index int) (res []int) {
copy(slice[index:], slice[index+1:])
return slice[:len(slice)-1]
}
根据具体应用场景选择适合的方法。例如:
package main
import (
"errors"
"fmt"
)
// 使用append的方法
func PopSliceElementByIndex(slice []int, index int) ([]int, error) {
if index < 0 || index >= len(slice) {
return nil, errors.New("index out of range")
}
return append(slice[:index], slice[index+1:]...), nil
}
// 使用copy的方法
func PopSliceElementByIndex2(slice []int, index int) ([]int, error) {
if index < 0 || index >= len(slice) {
return nil, errors.New("index out of range")
}
copy(slice[index:], slice[index+1:])
return slice[:len(slice)-1], nil
}
func main() {
slice := []int{1, 2, 3, 4, 5}
newSlice, err := PopSliceElementByIndex(slice, 2)
if err != nil {
fmt.Println("Error:", err)
} else {
fmt.Println("New slice (append method):", newSlice)
}
slice2 := []int{1, 2, 3, 4, 5}
newSlice2, err := PopSliceElementByIndex2(slice2, 2)
if err != nil {
fmt.Println("Error:", err)
} else {
fmt.Println("New slice (copy method):", newSlice2)
}
}
这样可以更清晰地看到两种方法的差异和选择依据。