blob: b0f4c6d040a697952cd47949e31855bd00137d95 [file] [log] [blame] [view]
Andrew Gerrand5bc444d2014-12-10 11:35:11 +11001Since the introduction of the ` append ` built-in, most of the functionality of the ` container/vector ` package, which was removed in Go 1, can be replicated using ` append ` and ` copy `.
2
3Here are the vector methods and their slice-manipulation analogues:
4
5` AppendVector `
6```
7a = append(a, b...)
8```
9` Copy `
10```
11b = make([]T, len(a))
12copy(b, a)
13// or
14b = append([]T(nil), a...)
15```
16` Cut `
17```
18a = append(a[:i], a[j:]...)
19```
20` Delete `
21```
22a = append(a[:i], a[i+1:]...)
23// or
24a = a[:i+copy(a[i:], a[i+1:])]
25```
26` Delete without preserving order `
27```
28a[i], a = a[len(a)-1], a[:len(a)-1]
29```
30**NOTE** 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. The following code can fix this problem:
31> ` Cut `
32```
33copy(a[i:], a[j:])
34for k, n := len(a)-j+i, len(a); k < n; k ++ {
35 a[k] = nil // or the zero value of T
36} // for k
37a = a[:len(a)-j+i]
38```
39> ` Delete `
40```
41copy(a[i:], a[i+1:])
42a[len(a)-1] = nil // or the zero value of T
43a = a[:len(a)-1]
44```
45> ` Delete without preserving order `
46```
47a[i], a[len(a)-1], a = a[len(a)-1], nil, a[:len(a)-1]
48```
49
50` Expand `
51```
52a = append(a[:i], append(make([]T, j), a[i:]...)...)
53```
54` Extend `
55```
56a = append(a, make([]T, j)...)
57```
58
59` Insert `
60```
61a = append(a[:i], append([]T{x}, a[i:]...)...)
62```
63**NOTE** The second ` append ` creates a new slice with its own underlying storage and copies elements in ` a[i:] ` to that slice, and these elements are then copied back to slice ` a ` (by the first ` append `). The creation of the new slice (and thus memory garbage) and the second copy can be avoided by using an alternative way:
64> ` Insert `
65```
66s = append(s, 0)
67copy(s[i+1:], s[i:])
68s[i] = x
69```
70
71` InsertVector `
72```
73a = append(a[:i], append(b, a[i:]...)...)
74```
75` Pop `
76```
77x, a = a[len(a)-1], a[:len(a)-1]
78```
79` Push `
80```
81a = append(a, x)
82```
83
84## Additional Tricks
85### Filtering without allocating
86
87This trick uses the fact that a slice shares the same backing array and capacity as the original, so the storage is reused for the filtered slice. Of course, the original contents are modified.
88
89```
90b := a[:0]
91for _, x := range a {
92 if f(x) {
93 b = append(b, x)
94 }
95}
96```