Go语言的切片(Slice)并不提供insert/delete API,但是在使用中,经常会出现在任意位置插入/删除一个元素的情况。

插入

假设原切片为s,在下标为index处插入元素value,实现如下:

1
2
3
// 这里保证 len(s) > 0 && index < len(s)
s = append(s[:index+1], s[index:]...)
s[index] = value

我们可以将这一动作封装成insert,如下:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
// 0 ≤ index ≤ len(s)
func insert(s []int, index int, value int) []int{
	if len(s) == index { // nil/empty slice or insert after last element
		s = append(s, value)
		return s
	}
	s = append(s[:index+1], s[index:]...) // index < len(s)
	s[index] = value
	return s
}

删除

1
2
3
4
// 0 ≤ index ≤ ≤ len(s)
func remove(s []int, index int) []int {
	return append(s[:index], s[index+1:]...)
}

示例:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package main

import "fmt"

func insert(s []int, index int, value int) []int {
	if len(s) == index { // nil/empty slice or insert after last element
		s = append(s, value)
		return s
	}
	s = append(s[:index+1], s[index:]...) // index < len(s)
	s[index] = value
	return s
}

func remove(s []int, index int) []int {
	return append(s[:index], s[index+1:]...)
}

func main() {
	s := []int{1, 2, 3, 5, 6}
	s = insert(s, 3, 4)
	fmt.Println(s) // [1 2 3 4 5 6]
	s = remove(s, len(s)-1)
	fmt.Println(s) // [1 2 3 4 5]
}

参考:

  1. https://stackoverflow.com/questions/46128016/insert-a-value-in-a-slice-at-a-given-index
  2. https://stackoverflow.com/questions/37334119/how-to-delete-an-element-from-a-slice-in-golang