-
要求一:能够实现删除操作就可以。
-
要求二:考虑使用比较高性能的实现。
-
要求三:改造为泛型方法
-
要求四:支持缩容,并旦设计缩容机制。
go
package main
import "fmt"
func DeleteAt[T any](slice []T, index int) []T {
if index < 0 || index > len(slice)-1 {
panic("index out of range")
}
// 前移
copy(slice[index:], slice[index+1:])
slice = slice[:len(slice)-1]
// 缩容
if cap(slice) >= len(slice)*2 {
newSlice := make([]T, len(slice))
copy(newSlice, slice)
return newSlice
}
return slice
}
func main() {
a := []int{1, 2, 3}
fmt.Println(DeleteAt(a, 2))
}
高性能操作直接在原切片对元素进行前移,然后截取;如果cap超过len的2倍,则创建一个起始长度容量更小的切片赋值