We use []int
in our examples but the code works for slices of all types.
https://codeeval.dev/gist/77f3972e670b06a70e650c9cda82e733
https://codeeval.dev/gist/ba44417fe5d9e227e7aa3a0b3724b20d
Note on efficiency: Go compiler is smart enough to re-use the space in the original slice, so this method is quite efficient. It doesn't allocate new space and merely copies the elements within the slice. We can verify this:
https://codeeval.dev/gist/e9489d9cfede37143a816eb167bd8d4e
%p
formatting directive prints the physical address in memory of a variable. We can verify that s
points to the same physical memory and has the same capacity before and after removal, so the underlying array.
We can also see that appending 4 elements, which is beyond remaining capacity of 2, caused the array to be re-allocated.
If we don't care to preserve the order of elements, we can optimize removal even further:
https://codeeval.dev/gist/b7c1cf23f4657ff78df71606eb0af732
We overwrite the element we want to remove with the last element in the slice and shrink the slice by 1.
This copies a single elements compared to copying all elements from i
to end of slice. This doesn't matter in small slices but is much faster if you have slices with thousands of elements