slices.go 596 B

12345678910111213141516171819202122232425
  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. return s // 越界保护
  8. }
  9. // 把 index+1 之后的元素整体前移 1 位,再截掉最后一个
  10. copy(s[index:], s[index+1:])
  11. return s[:len(s)-1]
  12. }
  13. func main() {
  14. s := []int{1, 2, 3, 4, 5}
  15. fmt.Println("原始:", s)
  16. s = remove(s, 2) // 删除下标 2(元素 3)
  17. fmt.Println("删除后:", s)
  18. s = remove(s, 0) // 再删除首元素
  19. fmt.Println("再删首元素:", s)
  20. }