How to delete an element from a slice in Golang

What are slices?

Slices are a built-in data type in Golang. They are similar to arrays, except that a slice has no specified length. All elements within a slice must have the same type.

The code below shows how to declare a slice literal with the string type specification.

newSlice := []string{"a", "b", "c", "d"}

How to delete an element from a slice

We can perform the following steps to delete an element from a slice while maintaining the order of the elements:

  1. Split the slice around the index that contains the element to delete so that neither of the two resulting slices contains this element.
  2. Use the built-in append method to join the new slices.

Example

Consider a slice that contains the values [1, 2, 3, 4] from which we want to remove the value 3.

First, we need to split the slice around the element 3 so that we get two resulting slices, [1, 2] and [4].

Next, we can append the two slices to get the desired result without the value 3, i.e., [1, 2, 4].

Code

The code below deletes the value "c" from a slice in Golang.

package main
import (
"fmt"
)
func main(){
// initialize a slice literal
originalSlice := []string{"a", "b", "c", "d"}
fmt.Println("The original slice is:", originalSlice)
// initialize the index of the element to delete
i := 2
// check if the index is within slice bounds
if i < 0 || i >= len(originalSlice) {
fmt.Println("The given index is out of bounds.")
} else {
// delete an element from the slice
newSlice := append(originalSlice[:i], originalSlice[i+1:]...)
fmt.Println("The new slice is:", newSlice)
}
}

Explanation

In the code above:

  • In line 4, we import the fmt package for printing.
  • In line 10, we initialize a slice literal of type string called originalSlice. At the time of declaration, originalSlice contains four values.
  • In line 14, we initialize the index of the element to delete from the slice.
  • The if statement in line 17 ensures that the index of the element to delete is within the valid range. In the case of originalSlice, the valid range of indices is between 0-3.
  • In line 21, originalSlice is split into two different slices around the index to remove, and these new slices are then merged through the append method.
originalSlice[:i] // This yields the slice elements before "c": ["a", "b"]

originalSlice[i+1:]... // This yields the elements after "c": "d"
  • Finally, the new slice is obtained as output.

Free Resources