Home >Backend Development >Golang >golang array delete element
In Golang, deleting array elements is a relatively troublesome task. Since the length of an array is determined when it is created, elements cannot be easily removed or added. In contrast, slices are a better choice because they can dynamically adjust length as needed. However, if you are already working with an array and need to remove some elements from it, here are some ways to achieve this.
The following is a sample code to implement this method:
func deleteElement(arr []int, index int) []int {
arr[index] = 0
return arr
}
The following is a sample code to implement this method:
func deleteElement(arr []int, index int) []int {
newSlice := make([] int, len(arr)-1)
copy(newSlice, arr[:index])
copy(newSlice[index:], arr[index 1:])
return newSlice
}
For example, the following code uses slices instead of arrays:
package main
import "fmt"
func main() {
var slice []int = []int{1, 2, 3, 4, 5, 6}
fmt.Println(slice) // [1 2 3 4 5 6]
slice = append(slice[ :2], slice[3:]...)
fmt.Println(slice) // [1 2 4 5 6]
}
Here, we first declare an int type slice and initialize its value. Then, use the append() function to remove elements from the slice.
Summary
Although deleting array elements in Golang is troublesome, it can be easily achieved using these three methods. If you need to add or remove elements frequently, it's better to use slicing. If you are not sure how to implement this, please refer to the sample code above.
The above is the detailed content of golang array delete element. For more information, please follow other related articles on the PHP Chinese website!