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"}
slice
We can perform the following steps to delete an element from a slice
while maintaining the order of the elements:
slice
around the index that contains the element to delete so that neither of the two resulting slices
contains this element.append
method to join the new slices
.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]
.
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)}}
In the code above:
fmt
package for printing.slice
literal of type string
called originalSlice
. At the time of declaration, originalSlice
contains four values.slice
.if
statement in line 17 ensures that the index of the element to delete is within the valid range. In the case of originalSlice
, the valid range of indices is between 0-3.originalSlice
is split into two different slices
around the index to remove, and these new slices
are then merged through the append
method.originalSlice[:i] // This yields the slice elements before "c": ["a", "b"]
originalSlice[i+1:]... // This yields the elements after "c": "d"
slice
is obtained as output.