slices.go 626 B

1234567891011121314151617181920212223242526
  1. package main
  2. import "fmt"
  3. // remove 返回删除了 index 处元素的新切片
  4. // 如果 index 越界,原样返回,不做删除
  5. func remove(s []int, index int) []int {
  6. if index < 0 || index >= len(s) {
  7. fmt.Println("数组越界")
  8. return s // 越界保护
  9. }
  10. // 把 index+1 之后的元素整体前移 1 位,再截掉最后一个
  11. copy(s[index:], s[index+1:])
  12. return s[:len(s)-1]
  13. }
  14. func main() {
  15. s := []int{1, 2, 3, 4, 5}
  16. fmt.Println("原始:", s)
  17. s = remove(s, 2) // 删除下标 2(元素 3)
  18. fmt.Println("删除后:", s)
  19. s = remove(s, 0) // 再删除首元素
  20. fmt.Println("再删首元素:", s)
  21. }