Open In App

Delete Elements in a Slice in Golang

Improve
Improve
Like Article
Like
Save
Share
Report

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. 



Last Updated : 13 Oct, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads