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

Extend Capacity

確保有空間附加 n 個元素,而不需要重新配置

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

Filter (原地)

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 會建立一個具有自己底層儲存的新切片,並將 a[i:] 中的元素複製到該切片,然後再將這些元素複製回切片 a(由第一個 append)。可以使用替代方法來避免建立新切片(以及記憶體垃圾)和第二次複製

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]

推入前端/取消移位

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

洗牌

費雪-耶茲演算法

自 Go 1.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 的一部分。