Go Slice Tricks Cheat Sheet、Go 切片使用小妙招

Go Slice Tricks Cheat Sheet 下载完整大图

If the type of the element is a pointer or a struct with pointer fields, which need to be garbage collected, the above implementations of Cut and Delete have a potential memory leak problem: some elements with values are still referenced by slice a and thus can not be collected.

total


移动端可能显示不全,请看上方的完整大图。

AppendVector

alen(a)cap(a)b

ab
a = append(a, b...)

Copy

ba
b = make([]T, len(a))
copy(b, a)

b = append([]T(nil), a...)

b = append(a[:0:0], a...)

Cut

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

Delete

ai
a = append(a[:i], a[i+1:]...)

a = a[:i+copy(a[i:], a[i+1:])]

Delete without preserving order

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

Cut (GC)

aijnilnil
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 (GC)

ainil
if i < len(a)-1 {
  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 (GC)

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

Expand

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

Extend

a
a = append(a, make([]T, j)...)

Filter (in place)

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

Insert

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

InsertVector

aab
a = append(a[:i], append(b, a[i:]...)...)

Push

a
a = append(a, x)

Pop

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

Push Front/Unshift

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

Pop Front/Shift

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

Go Slice Tricks Cheat Sheet (ueokande.github.io)

posted @ 2022-04-03 10:59  小能日记  阅读(19)  评论(0编辑  收藏  举报