remove an element from the middle of an array in go

To remove an element from the middle of an array in Go, you can use the slice technique. Here is an example of how to remove an element from the middle of an array:

main.go
func removeAtIndex(arr []int, index int) []int {
    return append(arr[:index], arr[index+1:]...)
}

func main() {
    // create an integer array
    arr := []int{1, 2, 3, 4, 5}

    // call the remove function to delete the element at index 2
    arr = removeAtIndex(arr, 2)

    // print the new array
    fmt.Println(arr)
}
327 chars
15 lines

The removeAtIndex function takes an integer array and an index as arguments. It then returns a new array that contains all of the elements of the original array except for the element at the given index. To do this, the function uses the slice technique by appending two slices together: arr[:index] (all elements up to the index) and arr[index+1:] (all elements after the index).

In the main function, we create an array of integers and pass it to the removeAtIndex function to remove the element at index 2. Finally, we print out the new array to confirm that the element has been removed.

related categories

gistlibby LogSnag