In this article, we will explore how to remove an item from a slice.
Golang Create Slice
We can create a slice in Go by specifying the data type of the elements it will hold. We can then enclose the items of the array inside a pair of curly braces.
The example code below shows how to create a slice in Go:
funcmain() {
slice := []string{"a","b","c","d"}
}
Once we have a slice declared, we can perform actions such as updating elements at a specific index, access the elements, add additional elements, and more. Check our tutorial on Golang slices to learn more.
Golang Delete Item
Before we discuss how to remove an item from a slice, let us discuss how we can create a sub-slice from a main slice. This is because it is important to understand how to remove an item from a slice.
We can create a sub-slice by using the indexing notation. For example, if we want to create a sub-slice comprised of the values from index 2 to 7, we can do:
The above syntax will grab the elements at index 2 to index 7 from the old slice and create a new slice.
If you want to create a sub-slice from index 0 to a target index, we can do:
The above syntax will take the elements from index 0 to index 5 and create a fresh slice.
Now that we have the process of creating a sub-slice from a slice out of the way, we can proceed with learning how to delete an element from a slice.
Preserve Slice Order
Suppose we have a slice containing elements as shown below:
If we want to remove an element from the slice and still preserve the order, we by shift the positions of the elements after the element we wish to remove towards the left with a factor of one.
We can express the above syntax as:
Where a represents the slice and i as the index of the element we wish to remove.
An example code is as shown:
import "fmt"
func main() {
slice := []string{"a", "b", "c", "d", "e", "f"}
index := 1
copy(slice[index:], slice[index+1:]) // shift valuesafter the indexwith a factor of 1
slice[len(slice)-1] = "" // remove element
slice = slice[:len(slice)-1] // truncateslice
fmt.Println(slice)
}
The code above will remove the element at index 0. The resulting slice is as shown:
Disregard the Slice Order
If reserving the slice order is not crucial, we can use the code as shown below:
import "fmt"
func main() {
slice := []string{"a", "b", "c", "d", "e", "f"}
index := 1
slice[index] = slice[len(slice)-1] // copy last element toindex we wish to remove
slice[len(slice)-1] = "" // remove the element
slice = slice[:len(slice)-1]
fmt.Println(slice)
}
The code above removes the element at the specified index. However, it does not retain the order of the slice as shown in the output below:
This because this method replaces the removed element with the element at the last index.
Conclusion
In this guide, we covered the basics of working with slices and how to remove an element from a slice with and without retaining the slice order.
Thanks for reading!