How to delete an element from an array in Golang
What are arrays in Golang?
Arrays are a built-in data type in Golang. An array can store a fixed number of elements of the same type.
The code below shows how to declare an array that can store up to elements with the string type specification.
newArray := [4]string{"a", "b", "c", "d"}
How to delete an element from an array
We can perform the following steps to delete an element from an array:
- Copy back each element of the original array in the right order except the element to delete.
- Reslice the array to remove the extra index.
Code
The code below deletes the value "c" from an array in Golang:
package mainimport ("fmt")func main(){// initialize an arrayoriginalArray := [4]string{"a", "b", "c", "d"}fmt.Println("The original array is:", originalArray)// initialize the index of the element to deletei := 2// check if the index is within array boundsif i < 0 || i >= len(originalArray) {fmt.Println("The given index is out of bounds.")} else {// delete an element from the arraynewLength := 0for index := range originalArray {if i != index {originalArray[newLength] = originalArray[index]newLength++}}// reslice the array to remove extra indexnewArray := originalArray[:newLength]fmt.Println("The new array is:", newArray)}}
Explanation
In the code above:
- In line 4, we import the
fmtpackage for printing. - In line 10, we initialize an array of type
stringcalledoriginalArray. At the time of declaration,originalArraycontains four values. - In line 14, we initialize the index of the element to delete from the array.
- The
ifstatement in line 17 ensures that the index of the element to delete is within the valid range. In the case oforiginalArray, the valid range of indices is between 0-3. - In line 21, we initialize a counter variable called
newLength, whose value will be incremented whenever we copy back a value into the array. - Line 22 uses a
forloop to iterate over each value in the array. - In line 23, we check if the current loop index matches the index of the element to delete. If not, then the value stored at the current loop index is copied to the index indicated by
newLength, and the value ofnewLengthis incremented. - Finally, in line 30, we copy all the values from
originalArraytonewArrayup until the index pointed to bynewLength.