Go Wiki: SliceTricks

自從引入了內建的 append 函式後,container/vector 包(在 Go 1 中已被移除)的大部分功能都可以透過 appendcopy 來複制。

自泛型引入以來,golang.org/x/exp/slices 包中提供了這些函式的一些泛型實現。

以下是 vector 的方法及其對應的 slice 操作模擬

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 的實現存在潛在的記憶體洩漏問題:一些元素的值仍然被 slice a 的底層陣列引用,只是在 slice 中“不可見”。因為被“刪除”的值在底層陣列中被引用,所以即使你的程式碼無法引用該值,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)...)

Extend Capacity (擴充套件容量)

確保有空間可以追加 n 個元素而無需重新分配

if cap(a)-len(a) < n {
    a = append(make([]T, 0, len(a)+n), a...)
}

Filter (in place) (原地過濾)

n := 0
for _, x := range a {
    if keep(x) {
        a[n] = x
        n++
    }
}
a = a[:n]

Insert

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

注意:第二個 append 會建立一個具有自己底層儲存的新 slice,並將 a[i:] 中的元素複製到該 slice,然後這些元素再由第一個 append 複製回 slice a。透過使用替代方法可以避免建立新 slice(從而避免記憶體垃圾)和第二次複製。

Insert

s = append(s, 0 /* use the zero value of the element type */)
copy(s[i+1:], s[i:])
s[i] = x

InsertVector

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

Push

a = append(a, x)

Pop

x, a = a[len(a)-1], a[:len(a)-1]

Push Front/Unshift (前置/左移)

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

Pop Front/Shift (前出/右移)

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

Additional Tricks (額外技巧)

Filtering without allocating (無分配過濾)

此技巧利用了 slice 與原始 slice 共享相同的底層陣列和容量的事實,因此儲存被用於過濾後的 slice。當然,原始內容會被修改。

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

對於必須進行垃圾回收的元素,可以在之後包含以下程式碼

clear(a[len(b):])

Reversing (反轉)

將 slice 的內容替換為相同的元素,但順序相反

for i := len(a)/2-1; i >= 0; i-- {
    opp := len(a)-1-i
    a[i], a[opp] = a[opp], a[i]
}

The same thing, except with two indices (相同功能,但有兩個索引)

for left, right := 0, len(a)-1; left < right; left, right = left+1, right-1 {
    a[left], a[right] = a[right], a[left]
}

Shuffling (打亂)

Fisher–Yates algorithm (費舍爾-耶茨演算法)

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

Batching with minimal allocation (批次處理,最小化分配)

如果您想對大型 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]]

In-place deduplicate (comparable) (原地去重 (可比較))

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]

Sliding Window (滑動視窗)

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