How do you remove a specific element from an array in Golang?
In Go language, the length of an array is immutable, so it is not possible to directly delete elements from an array. However, we can create a new array and copy the elements that are not to be deleted into the new array to “delete” the specified element. Here is an example code:
package main
import "fmt"
func removeElement(arr []int, elem int) []int {
result := make([]int, 0)
for _, val := range arr {
if val != elem {
result = append(result, val)
}
}
return result
}
func main() {
arr := []int{1, 2, 3, 4, 5}
elem := 3
newArr := removeElement(arr, elem)
fmt.Println(newArr) // 输出: [1 2 4 5]
}
In the above code, we have defined a function called removeElement, which takes an integer slice and an integer as parameters. Within the function, we create a new empty slice called result, then iterate through each element in the original slice arr. If an element is not equal to the element to be removed elem, it is appended to the new slice result. Finally, the function returns the new slice.
In the main function, we define an initial slice arr with an element to remove, which is 3. Next, we call the removeElement function and store the result in newArr. Finally, we print newArr, which will be the slice without the element 3.