The Wayback Machine - https://web.archive.org/web/20240920080406/https://www.geeksforgeeks.org/delete-elements-in-a-slice-in-golang/
Open In App

Delete Elements in a Slice in Golang

Last Updated : 13 Oct, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

A Slice in Golang is an array(list of elements of the same type) but it’s dynamic i.e. it can adjust its size as per the elements added throughout the program. We can initialize a slice without specifying the initial length or size, this allows us to add elements to it dynamically. So, there might be instances, where you need to remove elements from the slice. In Golang, the slice interface doesn’t have a built-in function for deleting elements in slices. So, in this article, we’ll be understanding how to delete elements in a slice.

Deleting Elements in a Slice 

To delete an element from a slice, we can’t directly remove an element from it, we need to perform certain copying of all elements in a different location and then relocate them to a new position in the original slice. To do this first we will construct a simple slice, populate it with elements and then delete an element based on its index. Given, the index of elements to delete from the slice, we will append all the elements after that index into a slice that contains all the elements before that index. This append operation will eventually modify the existing slice and remove the element by breaking the original slice into two slices and combining them again.

Using the append function to delete an element 

We create a slice and add elements to the slice, now we delete elements from it. So, we are going to delete the element by referencing its index of it in the slice. To delete the elements by referencing,  we will first create a variable for storing the index of an element, the index variable can also be taken in the form of input or passed from elsewhere. Using that index variable, we can access elements from the slice as we can see from the following example:

Go




// Go program to find the index of
// the element from the given slice
package main
 
import "fmt"
 
func main() {
     
    // Declaring an slice
    numbers := []int{10, 20, 30, 40, 50, 90, 60}
    fmt.Println("Slice:", numbers)
 
    var index int = 3
     
    // Get the element at a provided index in the slice
    elem := numbers[index]
    fmt.Println("Element at index 3 is:", elem)
}


Output:

Slice: [10 20 30 40 50 90 60]
Element at index 3 is: 40

So, at index 3, we have element 40 in the slice. Now, we will move into actually deleting the operation in the slice. 

We have to use the append function in Golang which will take two parameters. First is the slice itself to which we want to append, and the next parameter is what we want to append i.e. the elements to append into the slice. Here, we will append all the elements in a slice after the provided index into the slice with all the elements before the provided index.

numbers = append(numbers[:index], numbers[index+1:]…)

The above code will append the slice numbers[:index], since the index is 3, the numbers[:3] become [10, 20, 30]. And the slice which we are appending to numbers [3+1:] so it is [50, 90, 60]. Thereby we have excluded the element at the index = 3, by breaking the slice into two slices.

numbers = { 10, 20, 30, 40, 50, 90, 60 }
index   ->  0,  1 , 2 , 3 , 4 , 5 , 6
 

numbers[:index]  append  -> numbers[index+1]
        ^                            ^
        |                            |
    numbers[:3]                    numbers[4:]         
   [10, 20, 30]                   [50, 90, 60]                  (index = 3)
   
number = { 10, 20, 30, 50, 90, 60 }   -> element 40 (index = 3) deleted                  

Here, the slice becomes [10, 20, 30, 50, 90, 60], so we have removed element 40 at index 3 from the slice. So, syntactically we can convert this into a Golang script that appends the slices to the original array. Since the append function returns the modified slice we need to assign it to the original slice.

Go




// Go program to delete the element from the given slice
package main
import "fmt"
 
func main() {
     
    // Declaring a slice
    numbers := []int{10, 20, 30, 40, 50, 90, 60}
    fmt.Println("Original Slice:", numbers)
     
    var index int = 3
 
    // Get the element at the provided index in the slice
    elem := numbers[index]
     
    // Using append function to combine two slices
    // first slice is the slice of all the elements before the given index
    // second slice is the slice of all the elements after the given index
    // append function appends the second slice to the end of the first slice
    // returning a slice, so we store it in the form of a slice
    numbers = append(numbers[:index], numbers[index+1:]...)
 
    fmt.Printf("The element %d was deleted.\n", elem)
    fmt.Println("Slice after deleting elements:", numbers)
}


Output:

Original Slice: [10 20 30 40 50 90 60]
The element 40 was deleted.
Slice after deleting elements: [10 20 30 50 90 60]

Here we have added the … at the end of the parameter to the append function so as to indicate the passing of n number of arguments to the final parameter to the function. Here, since the slice allocation is dynamic, we have to pass it so as to pass n number of elements into the slice in the append function. 

The append function returns the slice after appending the elements into the slice, so we store the return value of the append function into the same original slice. here, we don’t create any extra slices explicitly, though the append function might create intermediate slices in order to append the slice into another.  

Example: We can now create a function that takes in the slice, the index of the element to be deleted, and returns the slice after deleting the element from the slice. The return type of the function will be the slice of that specific type of slice. Here, we will keep it int but it can be string, bool, and other valid data types in Golang. The function will take in parameters as the slice and the index of the element, so we construct the function as follows:

func delete_at_index(slice []int, index int) []int {

return append(slice[:index], slice[index+1:]…)

}

The function will take in two parameters i.e. a slice and the index which is the index of the element to be deleted. The function return type is []int which indicates a slice of type int. The function body is simple, it returns the call to function append. The append function takes in two parameters as we discussed in the above section and thus it returns the slice after deleting the element from the slice.

Go




// Go program to delete the element from the given slice
package main
 
import "fmt"
 
// Function that takes two parameters
// a slice which has to be operated on
// the index of the element to be deleted from the slice
// return value as a slice of integers
 
func delete_at_index(slice []int, index int) []int {
     
    // Append function used to append elements to a slice
    // first parameter as the slice to which the elements
    // are to be added/appended second parameter is the
    // element(s) to be appended into the slice
    // return value as a slice
    return append(slice[:index], slice[index+1:]...)
}
 
func main() {
     
    // Declaring a slice
    numbers := []int{10, 20, 30, 40, 50, 90, 60}
    fmt.Println("Original Slice:", numbers)
 
    var index int = 3
     
    // Get the element at a given index in the slice
    elem := numbers[index]
     
    // Call the function delete_at_index which
    // returns a slice of integers
    numbers = delete_at_index(numbers, index)
 
    fmt.Printf("The element %d was deleted.\n", elem)
    fmt.Println("Slice after deleting element:", numbers)
}


Output:

Original Slice: [10 20 30 40 50 90 60]
The element 40 was deleted.
Slice after deleting element: [10 20 30 50 90 60]

So, we are able to convert the simple script that deletes the element from the slice into a function. The function can be simply used to pass the slice and the index of the element and delete the element from the slice. 



Similar Reads

How to copy one slice into another slice in Golang?
A Slice is a variable-length sequence that stores elements of a similar type, you are not allowed to store different type of elements in the same slice. In Slice, you can copy one slice into another slice using the copy() function provided by the Go language. Or in other words, copy() function allows you to copy the elements of one slice into anoth
5 min read
How to join the elements of the byte slice in Golang?
In Go language slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. The slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice. In the Go slice of bytes, you are allowed to join the elements of the byte slice w
3 min read
How to replace all the elements in slice of bytes in Golang?
In Go language slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. The slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice. In the Go slice of bytes, you are allowed to replace all the elements in the given
3 min read
How to convert a slice of bytes in uppercase in Golang?
In Go language slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. The slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice. In the Go slice of bytes, you are allowed to convert a slice in the uppercase usin
2 min read
How to convert a slice of bytes in lowercase in Golang?
In Go language slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. The slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice. In the Go slice of bytes, you are allowed to convert a slice in the lowercase usin
2 min read
Check if the given slice is sorted in Golang
In Go language slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. The slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice. In Go language, you can check the given slice is sorted or not with the help of Sl
3 min read
Searching an element of float64 type in Golang slice
In Go language slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. The slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice. In the Go slice, you can search an element of float64 type in the given slice of f
3 min read
How to pass a Slice to Function in Golang?
Slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice. It is just like an array having an index value and length, but the size of the slice is resized they are not in fixed-size just like an array. In Go language, you are allowed to pass a slice to a fu
3 min read
How to Sort a Slice of Strings in Golang?
In Go language slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. The slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice. Go language allows you to sort the elements of the slice according to its type. So
3 min read
Check if the specified element is present in the slice of bytes in Golang
In Go language slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. The slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice. In the Go slice of bytes, you can check the given slice contain the specified elem
3 min read
How to count specific characters present in the slice in Golang?
In Go language slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. The slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice. In the Go slice of bytes, you can count the elements present in it with the help o
2 min read
How to sort a slice of ints in Golang?
In Go language slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. The slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice. Go language allows you to sort the elements of the slice according to its type. So
4 min read
How to sort a slice of float64s in Golang?
In Go language slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. The slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice. Go language allows you to sort the elements of the slice according to its type. So
3 min read
Checking Slice of bytes for equality under Unicode case folding in Golang
In Go language slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. The slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice. In the Go slice of bytes, you are allowed to compare two slices with each other wi
3 min read
Check if the Slice of bytes starts with specified prefix in Golang
In Go language slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. The slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice. In the Go slice of bytes, you can check whether the given slice begins with the sp
2 min read
Check if the Slice of bytes ends with specified suffix in Golang
In Go language slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. The slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice. In the Go slice of bytes, you can check whether the given slice ends with the spec
2 min read
How to replace a specified element in slice of bytes in Golang?
In Go language slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. The slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice. In the Go slice of bytes, you are allowed to replace a specified element in the gi
3 min read
How to repeat a slice of bytes in Golang?
In Go language slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. The slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice. In the Go slice of bytes, you are allowed to repeat the elements of the slice to a
3 min read
How to convert a slice of bytes in title case in Golang?
In Go language slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. The slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice. In the Go slice of bytes, you are allowed to convert a slice in the title case usi
2 min read
How to trim prefix from the slice of bytes in Golang?
In Go language slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. The slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice. In the Go slice of bytes, you are allowed to trim prefix from the given slice usin
3 min read
How to trim suffix from the slice of bytes in Golang?
In Go language slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. The slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice. In the Go slice of bytes, you are allowed to trim suffix from the given slice usin
3 min read
How to trim a slice of bytes in Golang?
In Go language slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. The slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice. In the Go slice of bytes, you are allowed to trim all the leading and trailing UTF
4 min read
How to split a slice of bytes in Golang?
In Go language slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. The slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice. In the Go slice of bytes, you are allowed to split the given slice using a Split()
3 min read
How to trim white spaces from the slice of bytes in Golang?
In Go language slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. The slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice. In the Go slice of bytes, you are allowed to trim all the leading and trailing whi
3 min read
How to trim left-hand side of a slice of bytes in Golang?
In Go language slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. The slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice. In the Go slice of bytes, you are allowed to trim all the starting UTF-8-encoded c
3 min read
How to trim right-hand side of a slice of bytes in Golang?
In Go language slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. The slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice. In the Go slice of bytes, you are allowed to trim all the ending UTF-8-encoded cod
3 min read
How to split a slice of bytes after the given separator in Golang?
In Go language slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. The slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice. In the Go slice of bytes, you are allowed to split the slice after the specified s
3 min read
Finding the index value of specified byte in slice of bytes in Golang
In Go language slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. The slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice. In the Go slice of bytes, you can find the first index value of the specified byte
3 min read
How to find the first index value in slice of bytes in Golang?
In Go language slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. The slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice. In the Go slice of bytes, you can find the first index value of the specified inst
3 min read
How to find the last index value in slice of bytes in Golang?
In Go language slice is more powerful, flexible, convenient than an array, and is a lightweight data structure.The slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice. In the Go slice of bytes, you can find the last index value of the specified instan
3 min read
Article Tags :