Delete an element from a slice by index

Avatar of the author Willem Schots
20 Jul, 2023 (Updated 16 Aug, 2023)
~2 min.
RSS

Directly deleting an element from a slice is not possible in Go. However, you can overwrite the element with later elements by using append.

s = append(s[:i], s[i+1:]...)

This should be read as: append “all elements that come after i” to “the elements up to i”.

Due to the way append works, this will not allocate a new backing array.

It’s important to reassign the slice returned by append, otherwise your s slice will contain duplicate data. See the last two elements in the backing array in the example below.

As a more concrete example, suppose you have the following food slice backed by array a.

a := [6]string{"", "🍎", "🍔", "🌭", "🍕", ""}
food := a[1:5]

To delete the element with index 1 (index 2 in the backing array) we would write the following code:

food = append(food[:1], food[2:])

If we diagram the steps taken, it would look like this:

food is a slice with backing array a. We want to delete the element containing "🍔"
food[0:1] is the slice we will append to.
food[2:4] are the elements that will be appended.
Calling append copies each appended element into the backing array.
append returns a new slice and we assign it to food.

Depending on your Go version there might already be a function that implements this code:

  • In 1.21 and later, use the Delete function in the slices package in the standard library.
  • For earlier versions, you can find the same function in the experimental slices package (also shown in the example below).

If you are using a Go version that does not support generics, you can always implement your own Delete function. See the example below:

main.go
package main

import (
	"fmt"
	"slices"
)

func main() {
	x := []string{"👁", "👃", "👁"}
	y := []string{"👁", "👃", "👁"}

	fmt.Println("x and y before", x, y)

	x = Delete(x, 1)
	y = slices.Delete(y, 1, 2)

	fmt.Println("x and y after", x, y)
}

func Delete(s []string, i int) []string {
	return append(s[:i], s[i+1:]...)
}
🎓

Subscribe to my Newsletter and Keep Learning.

Gain access to more content and get notified of the latest articles:

I send emails every 1-2 weeks and will keep your data safe. You can unsubscribe at any time.

Hello! I'm the Willem behind willem.dev

I created this website to help new Go developers, I hope it brings you some value! :)

You can follow me on Twitter/X, LinkedIn or Mastodon.

Thanks for reading!