How to delete an element from a slice in Golang
What are slices?
Slices are a built-in data type in Golang. They are similar to arrays, except that a slice has no specified length. All elements within a slice must have the same type.
The code below shows how to declare a slice literal with the string type specification.
newSlice := []string{"a", "b", "c", "d"}
How to delete an element from a slice
We can perform the following steps to delete an element from a slice while maintaining the order of the elements:
- Split the
slicearound the index that contains the element to delete so that neither of the two resultingslicescontains this element. - Use the built-in
appendmethod to join the newslices.
Example
Consider a slice that contains the values [1, 2, 3, 4] from which we want to remove the value 3.
First, we need to split the slice around the element 3 so that we get two resulting slices,
[1, 2] and [4].
Next, we can append the two slices to get the desired result without the value 3, i.e., [1, 2, 4].
Code
The code below deletes the value "c" from a slice in Golang.
package mainimport ("fmt")func main(){// initialize a slice literaloriginalSlice := []string{"a", "b", "c", "d"}fmt.Println("The original slice is:", originalSlice)// initialize the index of the element to deletei := 2// check if the index is within slice boundsif i < 0 || i >= len(originalSlice) {fmt.Println("The given index is out of bounds.")} else {// delete an element from the slicenewSlice := append(originalSlice[:i], originalSlice[i+1:]...)fmt.Println("The new slice is:", newSlice)}}
Explanation
In the code above:
- In line 4, we import the
fmtpackage for printing. - In line 10, we initialize a
sliceliteral of typestringcalledoriginalSlice. At the time of declaration,originalSlicecontains four values. - In line 14, we initialize the index of the element to delete from the
slice. - The
ifstatement in line 17 ensures that the index of the element to delete is within the valid range. In the case oforiginalSlice, the valid range of indices is between 0-3. - In line 21,
originalSliceis split into two differentslicesaround the index to remove, and these newslicesare then merged through theappendmethod.
originalSlice[:i] // This yields the slice elements before "c": ["a", "b"]
originalSlice[i+1:]... // This yields the elements after "c": "d"
- Finally, the new
sliceis obtained as output.