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"}
We can perform the following steps to delete an element from an array:
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)}}
In the code above:
fmt
package for printing.string
called originalArray
. At the time of declaration, originalArray
contains four values.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.newLength
, whose value will be incremented whenever we copy back a value into the array.for
loop to iterate over each value in the array.newLength
, and the value of newLength
is incremented.originalArray
to newArray
up until the index pointed to by newLength
.