How to Delete Elements in a Slice in Golang

In Go, there isn’t a built-in delete function for slices like maps. Instead, you usually use a combination of slice operations to remove an element from a slice.

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

  1. Using the “append() function” to delete an element
  2. Using the slices.Delete() function

Method 1: Using the append() function to delete an element

Let’s 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]

Note that this approach modifies the underlying array of the slice. If you have other slices that share the same underlying array, they might also be affected. If that’s a concern, you might want to make a copy of the slice before removing the element.

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 s slice. 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, but you can remove an element from the slice.