Deleting an Element from a Slice

Let’s learn how to delete an element from a slice.

There is no default function for deleting an element from a slice, which means that if we need to delete an element from a slice, we must write our own code.

How to delete an element from a slice

Deleting an element from a slice can be tricky, so this lesson presents two techniques for doing so. The first technique virtually divides the original slice into two slices, split at the index of the element that needs to be deleted. Neither of the two slices includes the element that is going to be deleted. After that, we concatenate these two slices and create a new one. The second technique copies the last element in the place of the element that is going to be deleted and creates a new slice by excluding the last element from the original slice.

Deletion: A graphical explanation

The next figure shows a graphical representation of the two techniques for deleting an element from a slice.

Get hands-on with 1400+ tech skills courses.