Go

How to delete an element from a Slice in Golang

25 September 2026 · 6 min read

How to delete an element from a Slice in Golang

Managing dynamic collections is a cornerstone of efficient Go programming. One of the most common operations you’ll encounter is deleting an element from a slice. While Go doesn’t offer a single, direct delete function like some other languages, it provides several elegant and performant approaches. Mastering these techniques will significantly enhance your ability to manipulate data structures and write cleaner, more efficient Go code. This article will delve into the various ways to delete an element from a slice in Go, covering best practices, performance considerations, and common pitfalls.

Understanding Go Slices

Before diving into deletion methods, it’s crucial to grasp how slices work in Go. A slice is a dynamic, reference-based data structure built upon an underlying array. It consists of a pointer to the array, the length of the slice, and its capacity. This structure allows slices to grow or shrink as needed, making them highly versatile. Understanding this underlying mechanism will help you choose the most appropriate deletion strategy.

Unlike arrays, which have a fixed size, slices can be resized using the built-in append function or by creating a new slice with a different length. This dynamic nature makes slices ideal for managing collections of data where the size may change during program execution. However, this flexibility comes with certain considerations when deleting elements, as we’ll explore in the following sections.

Deleting by Filtering

The most common and often preferred way to delete an element from a slice in Go is by filtering. This method involves creating a new slice containing only the elements you want to keep. It leverages the power of Go’s concise syntax for creating new slices based on existing ones.

For instance, to remove all even numbers from a slice of integers, you could use a simple loop and conditional check:

go package main import “fmt” func main() { nums := []int{1, 2, 3, 4, 5, 6} var oddNums []int for _, num := range nums { if num%2 != 0 { oddNums = append(oddNums, num) } } fmt.Println(oddNums) // Output: [1 3 5] } This approach creates a new slice oddNums containing only the odd numbers from the original nums slice. The original slice remains unchanged. This method is efficient and generally preferred for its clarity and simplicity.

Deleting by Index using copy and slicing

Another effective technique involves using the built-in copy function and slicing to remove an element at a specific index. This approach modifies the original slice in place.

Here’s how you can delete an element at index i:

go package main import “fmt” func main() { nums := []int{1, 2, 3, 4, 5} i := 2 // Index to delete copy(nums[i:], nums[i+1:]) nums = nums[:len(nums)-1] fmt.Println(nums) // Output: [1 2 4 5] } This method is particularly useful when you know the precise index of the element you need to remove. It efficiently shifts elements to fill the gap left by the deleted element and re-slices the original slice to its new, reduced length.

Deleting using append for in-place modification

While append is typically used for adding elements, it can also be employed for in-place deletion. This approach is less common but can be quite efficient, especially when dealing with larger slices.

To delete an element at index i, you can use the following:

go package main import “fmt” func main() { nums := []int{1, 2, 3, 4, 5} i := 2 // Index to delete nums = append(nums[:i], nums[i+1:]…) fmt.Println(nums) // Output: [1 2 4 5] } This single line of code effectively creates a new slice by appending the elements before the index i to the elements after i, thus excluding the element at index i. It’s a concise and performant way to achieve in-place deletion.

Handling Edge Cases

When deleting elements from a slice, it’s essential to consider edge cases, such as attempting to delete an element at an invalid index. Always ensure that the index you’re operating on is within the bounds of the slice. Failing to do so can lead to runtime panics.

Here’s an example of how to check for valid indices:

go package main import “fmt” func deleteAtIndex(nums []int, i int) []int { if i < 0 || i >= len(nums) { return nums // Return the original slice if the index is invalid } return append(nums[:i], nums[i+1:]…) } func main() { nums := []int{1, 2, 3, 4, 5} nums = deleteAtIndex(nums, 2) fmt.Println(nums) // Output: [1 2 4 5] nums = deleteAtIndex(nums, 10) // Invalid index fmt.Println(nums) // Output: [1 2 4 5] } This enhanced deleteAtIndex function ensures that the provided index is valid before attempting any deletion, preventing potential errors. This robust approach is crucial for writing reliable Go code.

Placeholder for infographic demonstrating slice deletion visually.

Frequently Asked Questions

  • What is the most efficient way to delete an element from a slice? It depends on the specific scenario. Filtering is generally preferred for its readability and is often efficient enough. However, for large slices and frequent deletions at known indices, the copy and slice or the append methods might offer slight performance advantages.
  • What happens if I try to delete an element at an invalid index? Attempting to access an element outside the bounds of a slice will result in a runtime panic. Always validate indices before performing deletion operations.

Go provides multiple ways to delete elements from slices, each with its own advantages and use cases. Understanding these different techniques allows you to choose the most appropriate method for your specific needs. By considering factors like code readability, performance requirements, and potential edge cases, you can write cleaner, more efficient, and robust Go programs. Explore the various methods outlined in this article, experiment with them in your own code, and discover further optimization strategies to enhance your Go programming skills. Remember to prioritize code clarity and error handling to build robust and maintainable applications.

Question & Answer :

fmt.Println("Enter position to delete::") fmt.Scanln(&pos) new_arr := make([]int, (len(arr) - 1)) k := 0 for i := 0; i < (len(arr) - 1); { if i != pos { new_arr[i] = arr[k] k++ i++ } else { k++ } } for i := 0; i < (len(arr) - 1); i++ { fmt.Println(new_arr[i]) } 

I am using this command to delete an element from a Slice but it is not working, please suggest.

Order matters

If you want to keep your array ordered, you have to shift all of the elements at the right of the deleting index by one to the left. Hopefully, this can be done easily in Golang:

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

However, this is inefficient because you may end up with moving all of the elements, which is costly.

Order is not important

If you do not care about ordering, you have the much faster possibility to replace the element to delete with the one at the end of the slice and then return the n-1 first elements:

func remove(s []int, i int) []int { s[i] = s[len(s)-1] return s[:len(s)-1] } 

With the reslicing method, emptying an array of 1 000 000 elements take 224s, with this one it takes only 0.06ns.

This answer does not perform bounds-checking. It expects a valid index as input. This means that negative values or indices that are greater or equal to the initial len(s) will cause Go to panic.

Slices and arrays being 0-indexed, removing the n-th element of an array implies to provide input n-1. To remove the first element, call remove(s, 0), to remove the second, call remove(s, 1), and so on and so forth.