Go Wiki:SliceTricks

自引入append内置函数以来,Go 1 中删除的container/vector软件包的大部分功能都可以使用appendcopy复制。

自引入泛型以来,golang.org/x/exp/slices软件包中提供了其中一些函数的泛型实现。

以下是矢量方法及其切片操作类似物

AppendVector

a = append(a, b...)

Copy

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...)

Cut

a = append(a[:i], a[j:]...)

Delete

a = append(a[:i], a[i+1:]...)
// or
a = a[:i+copy(a[i:], a[i+1:])]

Delete without preserving order

a[i] = a[len(a)-1] 
a = a[:len(a)-1]

注意如果元素的类型是指针或具有需要进行垃圾回收的指针字段的结构,则CutDelete的上述实现存在潜在的内存泄漏问题:一些具有值的元素仍由切片a的基础数组引用,只是在切片中“不可见”。由于基础数组中引用了“已删除”值,因此即使您的代码无法引用该值,该已删除值在 GC 期间仍然“可访问”。如果基础数组存在时间较长,则这表示存在泄漏。以下代码可以解决此问题

Cut

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]

Delete

copy(a[i:], a[i+1:])
a[len(a)-1] = nil // or the zero value of T
a = a[:len(a)-1]

Delete without preserving order

a[i] = a[len(a)-1]
a[len(a)-1] = nil
a = a[:len(a)-1]

Expand

在位置i插入n个元素

a = append(a[:i], append(make([]T, n), a[i:]...)...)

Extend

追加 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 创建了一个新的切片,具有自己的底层存储,并将 a[i:] 中的元素复制到该切片,然后将这些元素复制回切片 a(通过第一个 append)。可以通过使用替代方法来避免创建新的切片(因此避免内存垃圾)和第二次复制

插入

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]

压入前端/取消移位

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

弹出前端/移位

x, a = a[0], a[1:]

其他技巧

不分配的过滤

此技巧利用了这样一个事实:切片与原始切片共享相同的支持数组和容量,因此存储会被重复用于经过过滤的切片。当然,原始内容会被修改。

b := a[:0]
for _, x := range a {
    if f(x) {
        b = append(b, x)
    }
}

对于必须进行垃圾回收的元素,可以在之后包含以下代码

for i := len(b); i < len(a); i++ {
    a[i] = nil // or the zero value of T
}

反转

用相同元素替换切片的内容,但顺序相反

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]
}

批量处理,分配最少

如果您想对大切片进行批量处理,此方法很有用。

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 的一部分。