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:]...)
}

Career choice: Learn skills to mitigate the upcoming AI privacy disaster*

Join 800+ devs reading my newsletter

*Everyone and their mother is sending sensitive data to AI systems with little concern for their privacy. If you read the fineprint, vendors and platforms actually offer very little guarantees. It's a matter of time before it goes wrong.

From March 2026 onwards, I'll be writing about development of verifiably-secure services using OpenPCC.

Avatar of the author
Willem Schots

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 Bluesky, Twitter/X or LinkedIn.

Thanks for reading!