jack 4 месяцев назад
Родитель
Сommit
626f6be421
2 измененных файлов с 28 добавлено и 0 удалено
  1. 3 0
      golang-learn/10-slices/go.mod
  2. 25 0
      golang-learn/10-slices/slices.go

+ 3 - 0
golang-learn/10-slices/go.mod

@@ -0,0 +1,3 @@
+module slices
+
+go 1.22.2

+ 25 - 0
golang-learn/10-slices/slices.go

@@ -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)
+}