|
|
@@ -0,0 +1,25 @@
|
|
|
+package main
|
|
|
+
|
|
|
+import "fmt"
|
|
|
+
|
|
|
+// remove 返回删除了 index 处元素的新切片
|
|
|
+// 如果 index 越界,原样返回,不做删除
|
|
|
+func remove(s []int, index int) []int {
|
|
|
+ if index < 0 || index >= len(s) {
|
|
|
+ return s // 越界保护
|
|
|
+ }
|
|
|
+ // 把 index+1 之后的元素整体前移 1 位,再截掉最后一个
|
|
|
+ copy(s[index:], s[index+1:])
|
|
|
+ return s[:len(s)-1]
|
|
|
+}
|
|
|
+
|
|
|
+func main() {
|
|
|
+ s := []int{1, 2, 3, 4, 5}
|
|
|
+ fmt.Println("原始:", s)
|
|
|
+
|
|
|
+ s = remove(s, 2) // 删除下标 2(元素 3)
|
|
|
+ fmt.Println("删除后:", s)
|
|
|
+
|
|
|
+ s = remove(s, 0) // 再删除首元素
|
|
|
+ fmt.Println("再删首元素:", s)
|
|
|
+}
|