remove an element from an array at a specific index in go

To remove an element from an array at a specific index in Golang, you can convert the array to a slice, remove the element from the slice, and then convert back to an array. Here's an example:

main.go
// create an array with 5 elements
arr := [5]int{1, 2, 3, 4, 5}

// convert the array to a slice
slice := arr[:]

// remove the element at index 2
slice = append(slice[:2], slice[3:]...)

// convert the slice back to an array
arr = [5]int{}
copy(arr[:], slice)

fmt.Println(arr) // [1 2 4 5 0]
294 chars
15 lines

In the example above, we first create an array with 5 elements. We then convert the array to a slice using the [:] syntax. Next, we remove the element at index 2 from the slice using the append function and slicing the slice into 2 parts before and after the element we want to remove. Finally, we convert the slice back to an array using the copy function. The output is the resulting array with the element removed at the specified index.

related categories

gistlibby LogSnag