delete

golang对于slice删除元素比较麻烦,主要有两种

不保留顺序

1
2
3
a[i] = a[len(a)-1]
a[len(a)-1] = nil // zero value, nil、0 etc.
a = a[:len(a)-1]

保留顺序

1
2
3
copy(a[i:],a[i+1:])
a[len(a)-1] = nil // zero value
a = a[:len(a)-1]

insert

先扩后搬最后插

1
2
3
a = append(a, nil)
copy(a[i+1:],a[i:])
a[i] = x

push & pop

贴片操作即可解决

1
2
3
4
5
a = append(a, x)
x, a = a[len(a)-1], a[:len(a)-1]

a = append([]T{x},a...)
a = a[0], a[1:]

整体测试

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
a := []string{"A", "B", "C", "D", "E"}
i := 2
a[i] = a[len(a)-1]
a[len(a)-1] = "" // zero value, nil、0 ect.
a = a[:len(a)-1]
fmt.Println(a)

a = []string{"A", "B", "C", "D", "E"}
copy(a[i:], a[i+1:])
a[len(a)-1] = "" // zero value
a = a[:len(a)-1]
fmt.Println(a)

a = []string{"A", "B", "C", "D", "E"}
a = append(a, "")
copy(a[i+1:], a[i:])
a[i] = "F"
fmt.Println(a)

// Push Front
a = []string{"A", "B", "C", "D", "E"}
a = append([]string{"F"}, a...)
fmt.Println(a)

参考

SliceTricks