Go Wiki: 切片技巧
自从引入内置函数 append
后,container/vector
包(在 Go 1 中已移除)的大部分功能可以使用 append
和 copy
来重现。
自从引入泛型后,其中几个函数的泛型实现可在 golang.org/x/exp/slices
包中找到。
以下是 vector 方法及其对应的 slice 操作
追加向量
a = append(a, b...)
复制
b := make([]T, len(a))
copy(b, a)
// These two are often a little slower than the above one,
// but they would be more efficient if there are more
// elements to be appended to b after copying.
b = append([]T(nil), a...)
b = append(a[:0:0], a...)
// This one-line implementation is equivalent to the above
// two-line make+copy implementation logically. But it is
// actually a bit slower (as of Go toolchain v1.16).
b = append(make([]T, 0, len(a)), a...)
剪切
a = append(a[:i], a[j:]...)
删除
a = append(a[:i], a[i+1:]...)
// or
a = a[:i+copy(a[i:], a[i+1:])]
无序删除
a[i] = a[len(a)-1]
a = a[:len(a)-1]
注意 如果元素的类型是指针或包含指针字段的结构体,且需要进行垃圾回收,那么上述 Cut
和 Delete
的实现可能存在潜在的内存泄漏问题:一些包含值的元素仍然被 slice a
的底层数组引用,只是在 slice 中“不可见”。因为“已删除”的值在底层数组中被引用,即使代码无法引用该值,它在 GC 期间仍然“可达”。如果底层数组生命周期很长,这就会导致内存泄漏。以下代码可以解决此问题
剪切
copy(a[i:], a[j:])
for k, n := len(a)-j+i, len(a); k < n; k++ {
a[k] = nil // or the zero value of T
}
a = a[:len(a)-j+i]
删除
copy(a[i:], a[i+1:])
a[len(a)-1] = nil // or the zero value of T
a = a[:len(a)-1]
无序删除
a[i] = a[len(a)-1]
a[len(a)-1] = nil
a = a[:len(a)-1]
扩展
在位置 i
插入 n
个元素
a = append(a[:i], append(make([]T, n), a[i:]...)...)
扩展
追加 n
个元素
a = append(a, make([]T, n)...)
扩容
确保有足够的空间追加 n
个元素而无需重新分配内存
if cap(a)-len(a) < n {
a = append(make([]T, 0, len(a)+n), a...)
}
过滤 (原地操作)
n := 0
for _, x := range a {
if keep(x) {
a[n] = x
n++
}
}
a = a[:n]
插入
a = append(a[:i], append([]T{x}, a[i:]...)...)
注意:第二个 append
会创建一个具有独立底层存储的新 slice,并将 a[i:]
中的元素复制到该 slice 中,然后这些元素再被复制回 slice a
(由第一个 append
完成)。创建新 slice(以及因此产生的内存垃圾)和第二次复制可以通过使用替代方法来避免。
插入
s = append(s, 0 /* use the zero value of the element type */)
copy(s[i+1:], s[i:])
s[i] = x
插入向量
a = append(a[:i], append(b, a[i:]...)...)
// The above one-line way copies a[i:] twice and
// allocates at least once.
// The following verbose way only copies elements
// in a[i:] once and allocates at most once.
// But, as of Go toolchain 1.16, due to lacking of
// optimizations to avoid elements clearing in the
// "make" call, the verbose way is not always faster.
//
// Future compiler optimizations might implement
// both in the most efficient ways.
//
// Assume element type is int.
func Insert(s []int, k int, vs ...int) []int {
if n := len(s) + len(vs); n <= cap(s) {
s2 := s[:n]
copy(s2[k+len(vs):], s[k:])
copy(s2[k:], vs)
return s2
}
s2 := make([]int, len(s) + len(vs))
copy(s2, s[:k])
copy(s2[k:], vs)
copy(s2[k+len(vs):], s[k:])
return s2
}
a = Insert(a, i, b...)
推入
a = append(a, x)
弹出
x, a = a[len(a)-1], a[:len(a)-1]
前端推入/Unshift
a = append([]T{x}, a...)
前端弹出/Shift
x, a = a[0], a[1:]
更多技巧
无需分配内存的过滤
这个技巧利用了 slice 与原始 slice 共享同一底层数组和容量的事实,因此过滤后的 slice 重用了存储空间。当然,原始内容会被修改。
b := a[:0]
for _, x := range a {
if f(x) {
b = append(b, x)
}
}
对于必须进行垃圾回收的元素,之后可以包含以下代码
clear(a[len(b):])
反转
将 slice 的内容替换为相同元素但顺序相反
for i := len(a)/2-1; i >= 0; i-- {
opp := len(a)-1-i
a[i], a[opp] = a[opp], a[i]
}
同样的操作,但使用两个索引
for left, right := 0, len(a)-1; left < right; left, right = left+1, right-1 {
a[left], a[right] = a[right], a[left]
}
洗牌
Fisher–Yates 算法
自 go1.10 起,此功能可在 math/rand.Shuffle 中使用。
for i := len(a) - 1; i > 0; i-- {
j := rand.Intn(i + 1)
a[i], a[j] = a[j], a[i]
}
最大限度减少内存分配的分批处理
如果您想对大型 slice 进行分批处理,此方法很有用。
actions := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
batchSize := 3
batches := make([][]int, 0, (len(actions) + batchSize - 1) / batchSize)
for batchSize < len(actions) {
actions, batches = actions[batchSize:], append(batches, actions[0:batchSize:batchSize])
}
batches = append(batches, actions)
结果如下
[[0 1 2] [3 4 5] [6 7 8] [9]]
原地去重 (可比较类型)
import "sort"
in := []int{3,2,1,4,3,2,1,4,1} // any item can be sorted
sort.Ints(in)
j := 0
for i := 1; i < len(in); i++ {
if in[j] == in[i] {
continue
}
j++
// preserve the original data
// in[i], in[j] = in[j], in[i]
// only set what is required
in[j] = in[i]
}
result := in[:j+1]
fmt.Println(result) // [1 2 3 4]
移至头部,如果不存在则添加到头部,尽可能原地操作。
// moveToFront moves needle to the front of haystack, in place if possible.
func moveToFront(needle string, haystack []string) []string {
if len(haystack) != 0 && haystack[0] == needle {
return haystack
}
prev := needle
for i, elem := range haystack {
switch {
case i == 0:
haystack[0] = needle
prev = elem
case elem == needle:
haystack[i] = prev
return haystack
default:
haystack[i] = prev
prev = elem
}
}
return append(haystack, prev)
}
haystack := []string{"a", "b", "c", "d", "e"} // [a b c d e]
haystack = moveToFront("c", haystack) // [c a b d e]
haystack = moveToFront("f", haystack) // [f c a b d e]
滑动窗口
func slidingWindow(size int, input []int) [][]int {
// returns the input slice as the first element
if len(input) <= size {
return [][]int{input}
}
// allocate slice at the precise size we need
r := make([][]int, 0, len(input)-size+1)
for i, j := 0, size; j <= len(input); i, j = i+1, j+1 {
r = append(r, input[i:j])
}
return r
}
此内容是 Go Wiki 的一部分。