Delete Elements in a Slice in Golang
Last Updated :
13 Oct, 2022
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
package main
import "fmt"
func main() {
numbers := []int{ 10 , 20 , 30 , 40 , 50 , 90 , 60 }
fmt.Println( "Slice:" , numbers)
var index int = 3
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
package main
import "fmt"
func main() {
numbers := []int{ 10 , 20 , 30 , 40 , 50 , 90 , 60 }
fmt.Println( "Original Slice:" , numbers)
var index int = 3
elem := numbers[index]
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
package main
import "fmt"
func delete_at_index(slice []int, index int) []int {
return append(slice[:index], slice[index+ 1 :]...)
}
func main() {
numbers := []int{ 10 , 20 , 30 , 40 , 50 , 90 , 60 }
fmt.Println( "Original Slice:" , numbers)
var index int = 3
elem := numbers[index]
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 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 ar
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 ar
3 min read
How to Get First and Last Element of Slice in Golang?
Go language slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. 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 inde
2 min read
Searching an element of string 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
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
3 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 ar
3 min read
How to append a slice in Golang?
In Go, slices are dynamically-sized, flexible views into the elements of an array. Appending elements to a slice is a common operation that allows for the expansion of the slice as needed. The built-in append function is used to add elements to the end of a slice.In this article,we will learn How to
2 min read
How to Delete or Remove a File in Golang?
In the Go language, you are allowed to remove the existing file with the help of the Remove() method. This method removes the specified file from the director or it also removes empty directories. If the given path is incorrect, then it will throw an error of type *PathError. It is defined under the
1 min read
How to Create and Print Multi Dimensional Slice 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. Inter
2 min read
Golang | Searching an element of int type in slice of ints
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
3 min read