# Delete Elements from a Slice in Go with slices.Delete

> Remove elements from a Go slice by index range with slices.Delete or by a filter condition with slices.DeleteFunc, with examples for both approaches

**URL:** https://sentry.io/answers/deleting-an-element-from-a-slice-in-go/

---

## The Problem

You don't know how to delete an element from a slice in Go.

## The Solution

If you know the index of the element(s) that you want to delete from a slice, you can use the [`Delete`](https://pkg.go.dev/slices#Delete) function from the [`slices`](https://pkg.go.dev/slices) package.

**Note:** The [`slices.Delete`](https://pkg.go.dev/slices#Delete) function is `O(len(s)-i)`, where `i` represents the start of the range to be deleted. If you need to delete many items, it is better to delete them all in a single call than to delete one item at a time. This function also expects the input to be valid.

```go
package main

import (
	"fmt"
	"slices"
)

func main() {
	letters := []string{"a", "b", "c", "d", "e"}
	letters = slices.Delete(letters, 1, 4)
	fmt.Println(letters)
}
```

This prints:

```
[a e]
```

Attempting to delete an invalid range will cause a panic, as in the example below:

```go
package main

import (
	"fmt"
	"slices"
)

func main() {
	letters := []string{"a", "b", "c", "d", "e"}
	letters = slices.Delete(letters, 1, 10)
}
```

Because `10` is an invalid index, this returns the following panic:

```
panic: runtime error: slice bounds out of range [:10:5]
```

### Searching for Elements

If you want to search for specific elements in a slice, you can use the [`slices.DeleteFunc`](https://pkg.go.dev/slices#DeleteFunc) instead.

For example, you could search for all the even numbers in a slice as follows:

```go
package main

import (
	"fmt"
	"slices"
)

func main() {
	example := []int{0, 1, 2, 3, 4, 5, 6}
	example = slices.DeleteFunc(example, func(n int) bool {
		return n%2 != 0 // Remove odd numbers.
	})

	fmt.Println(example)
}
```

This prints an output of the slice with the odd numbers removed:

```
[0 2 4 6]
```

**Note:** This example passes the `func(n int)` filter function to `slices.DeleteFunc`. Because this is a generic filter function, its argument must match the type of the slice. In this case, it accepts an `int` because `example` is a slice of integers. If you instead wanted to filter a specific string from strings, you would change the argument of the filter function to `string`:

```go
package main

import (
	"fmt"
	"slices"
)

func main() {
	example := []string{"a", "b", "c"}
	example = slices.DeleteFunc(example, func(s string) bool {
		return s == "b"
	})

	fmt.Println(example)
}
```

This would print:

```
[a c]
```

## Further Reading

- The [Go `slices`](https://pkg.go.dev/slices) package
- The [Go Slices: usage and internals](https://go.dev/blog/slices-intro) blog post

---

*Source: [sentry.io/answers/deleting-an-element-from-a-slice-in-go/](https://sentry.io/answers/deleting-an-element-from-a-slice-in-go/)*
