remove an item from an array in go

To remove an item from an array in Go, we can use the built-in function append. The idea is to copy all the elements of the original array into a new slice, except for the item we want to remove. Here is an example code snippet:

main.go
package main

import "fmt"

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

func main() {
    arr := []int{1, 2, 3, 4, 5}
    index := 2
    fmt.Println("Original array:", arr)

    arr = removeElement(arr, index)
    fmt.Println("Array after removing element at index", index, ":", arr)
}
343 chars
17 lines

In this example, the function removeElement takes an array as input along with the index of the element to be removed. It returns a new slice that contains all elements of the original array except for the element at the specified index.

To achieve this, we use the append function with the following arguments:

  • The first argument is a slice that contains all elements of the original array up to the index of the element to be removed.
  • The second argument is a slice that contains all elements of the original array starting from the index of the element to be removed, up to the end of the array.

With these two slices combined, append returns a new slice that contains all elements of the original array except for the one at the specified index.

gistlibby LogSnag