How to Delete an Element from a Slice in Golang

There are two ways to delete an element from a slice in Go.

  1. Method 1: Using the combination of slice operations
  2. Method 2: Using the slices.Delete() function

Method 1: Using the combination of slice operations

To delete an element from a slice in Golang, you can use a combination of slice operations.

Syntax

func deleteElement(slice []int, s int) []int {
  return append(slice[:s], slice[s+1:]...)
}

Example

Here’s a function that demonstrates how to delete an element from a slice by its index:

package main

import (
  "fmt"
)

func deleteElement(slice []int, index int) []int {
  if index < 0 || index >= len(slice) {
    fmt.Println("Index out of range")
    return slice
  }

  return append(slice[:index], slice[index+1:]...)
}

func main() {
  mainSlice := []int{11, 21, 19, 18, 46}
  fmt.Println("Before deletion:", mainSlice)

  mainSlice = deleteElement(mainSlice, 3)
  fmt.Println("After deletion:", mainSlice)
}

Output

Before deletion: [11 21 19 18 46]
After deletion: [11 21 19 46]

In the deleteElement() function, we checked if the index was valid. If it’s not, we return the original slice.

Then, we used the append() function to concatenate the two parts of the slice: the elements before the index and the elements after the index.

The … (ellipsis) syntax is used to unpack the second part of the slice as individual elements to be appended to the first part.

The slice index starts from 0, and we passed index 3, which means the 4th element of the slice will be removed, which it did!

Note that this method does not modify the original slice in place but creates a new one.

Remember that if you work with large slices, this method may cause performance issues due to memory allocations and copying.

Method 2: Using the slices.Delete() function

The slices.Delete() function removes the elements s[i:j] from s, returning the modified slice.

Delete() function panics if s[i:j] is not a valid slice of s. Delete modifies the contents of the slice s; it does not create a new slice. 

Example

package main

import (
  "fmt"
  "golang.org/x/exp/slices"
)

func main() {
  mainSlice := []int{11, 21, 19, 18, 46}
  fmt.Println("Before deletion:", mainSlice)

  mainSlice = slices.Delete(mainSlice, 3, 4)
  fmt.Println("After deletion:", mainSlice)
}

Output

Before deletion: [11 21 19 18 46]
After deletion: [11 21 19 46]

It’s an experiment package’s function right now, but you can use this function to remove an element from the slice. That’s it.

Leave a Comment