Removing an element from a slice is not particularly intuitive in Go. Unlike other languages, Go does not provide a built-in function for this purpose. If you're wondering how an element may be removed from a Go slice, the code snippets below should provide the answers you seek.
Let’s consider a few strategies to remove elements from a slice in Go. The first two sections below assume that you want to modify the slice in place. If you want to create a copy of the slice with the element removed, while leave the original as is, please jump to the Preserve the original slice section below.
If slice order is unimportant
If the order of the elements in a slice is not important, you can copy the last element to the index that you want to remove, then truncate the slice up until the last element as shown below:
A variation of the above solution which is potentially more readable is to copy the first element to the specified index, then truncate the slice from the second index. A subtle difference with this solution compared to the previous one is that the capacity of the slice is not preserved which makes this method potentially less performant if you’ll be appending to the slice later.
In general, prefer the first approach to the second unless you’re sure you won’t be appending to the slice later.
If slice order is important
If you want to maintain the order of the elements in the slice, you can use the following technique known as re-slicing which leverages the built-in append function:
This method is more expensive than the first one because you’re joining two new slices together to create a third one using append as opposed to one assignment and one copy in the previous section.
Preserve the original slice
Both solutions discussed above modify the original slice in one way or another. If this is not desired, you need to create a brand new slice with a different underlying array before appending to it. Make sure to assign the result of removeElement to a new variable as well to maintain access to the original.
Here’s a variant of the re-slicing method that leaves the original slice passed to removeElement unmodified:
As you can see, this solution preserves the original s slice after removeElement is called, and further modifications of ns after the fact doesn’t cause s to change as well.
Remove elements from a slice while iterating
If you want to remove multiple elements from a slice in Go while iterating over it, make sure that you’re iterating from the end of the slice to the start. If you do it the other way round, your program will panic with an index out of bounds error due to the fact that the slice length keeps decreasing each time an element is removed.
Here’s an example that removes all even integers from a slice:
You should be able to use the techniques presented above to solve any problem that involves removing an element from a slice in Go. If you have any further contribution, please leave a comment below.