This is a creation in Article, where the information may have evolved or changed.
This is a summary of the official Golang: slicetricks
Due to the introduction of the built-in append
approach, container/vector
many of the package's methods are removed and can be replaced by built-in append
and copy
methods.
The following is the implementation of the operation method of the stack vector, using slice to implement related operations.
Appendvector
Copy
1234 |
Make Len (a)) Copy (b, a) //If A is not empty, you can also use the following method Append ([]t (nil), a ...) |
Cut
Cut off a piece of data
1 |
Append (A[:i], a[j:] ...) |
Delete
Delete an element
123 |
Append (A[:i], a[i+1:] ...) //ora = a[:i+copy(a[i:], a[i+1:])] |
Delete, but do not keep the original order
12 |
A[i] = a[len(a)-1] A = a[:len(a)-1] |
Note : If the element is a pointer, or a struct containing a pointer field, the cut
delete
implementation may have a potential memory leak. The values of some elements may be referenced all the time without a
being released, and the following code will solve the problem.
Cut
12345 |
Copy (a[i:], A[j:]) for Len Len Nil //or the zero value of T} A = a[:len(a)-j+i] |
Delete
123 |
Copy (a[i:], a[i+1:]) a[Len(a)-1nil//or the zero value of Ta = a[:len( A)-1] |
Delete, but do not keep the original order
123 |
A[i] = a[len(a)-1]a[len(a)-1nila = a[:len(a)-1] |
Expand
Insert a section into the middle
1 |
Append Append (make ([]t, J), A[i:] ...) ...) |
Extend
Insert a section to the tail
1 |
Append Make ([]t, J) ...) |
Insert
1 |
Append Append ([]t{x}, A[i:] ...) ...) |
Note : The second append
will use its underlying storage to create a new slice, then copy it a[i:]
to this slice and then copy the slice back s
. The creation of new slice and the second copy can be avoided using the following methods:
Insert
123 |
Append (s, 0) Copy (S[i+1:], S[i:]) s[i] = X |
Insertvector
1 |
Append Append (b, A[i:] ...) ...) |
Pop
1 |
X, a = a[len(a)-1], a[:Len(a)-1] |
Push
Shift
Unshift
Other tricks
Filter with no additional object assignments
This technique leverages the slice to share its underlying data storage and capacity.
123456 |
B: = a[: 0]forrange a {ifappend(b, x)}} |
Reverse
Reverses the elements in the slice.
1234 |
for Len (a) /2 -1; I >= 0Len(a)-1-ia[i], A[opp] = A[opp], A[i]} |
The following code is similar, except that two index variables are used
123 |
for Left, right: = 0Len(a)-1; Left < right; Left, right = left+1, right-1 {a[left], a[right] = A[right], A[left]} |