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
andDelete
have a potential memory leak problem: some elements with values are still referenced by slicea
and thus can not be collected.
移动端可能显示不全,请看上方的完整大图。
AppendVector
a = append(a, b...)
Copy
b = make([]T, len(a))
copy(b, a)
b = append([]T(nil), a...)
b = append(a[:0:0], a...)
Cut
a = append(a[:i], a[j:]...)
Delete
a = append(a[:i], a[i+1:]...)
a = a[:i+copy(a[i:], a[i+1:])]
Delete without preserving order
a[i] = a[len(a)-1]
a = a[:len(a)-1]
Cut (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]
Delete (GC)
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)
a[i] = a[len(a)-1]
a[len(a)-1] = nil
a = a[:len(a)-1]
Expand
a = append(a[:i], append(make([]T, j), a[i:]...)...)
Extend
a = append(a, make([]T, j)...)
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:]...)...)
InsertVector
a = append(a[:i], append(b, a[i:]...)...)
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:]
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!