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 44 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:

  1. Copy back each element of the original array in the right order except the element to delete.
  2. Reslice the array to remove the extra index.

Code

The code below deletes the value "c" from an array in Golang:

package main
import (
"fmt"
)
func main(){
// initialize an array
originalArray := [4]string{"a", "b", "c", "d"}
fmt.Println("The original array is:", originalArray)
// initialize the index of the element to delete
i := 2
// check if the index is within array bounds
if i < 0 || i >= len(originalArray) {
fmt.Println("The given index is out of bounds.")
} else {
// delete an element from the array
newLength := 0
for index := range originalArray {
if i != index {
originalArray[newLength] = originalArray[index]
newLength++
}
}
// reslice the array to remove extra index
newArray := originalArray[:newLength]
fmt.Println("The new array is:", newArray)
}
}

Explanation

In the code above:

  • In line 4, we import the fmt package for printing.
  • In line 10, we initialize an array of type string called originalArray. At the time of declaration, originalArray contains four values.
  • In line 14, we initialize the index of the element to delete from the array.
  • The if statement in line 17 ensures that the index of the element to delete is within the valid range. In the case of originalArray, 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 for loop 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 of newLength is incremented.
  • Finally, in line 30, we copy all the values from originalArray to newArray up until the index pointed to by newLength.

Free Resources