OneBite.Dev - Coding blog in a bite size

insert an element at a specific index in an array in Go

Code snippet on how to insert an element at a specific index in an array in Go

func InsertAtIndex(arr []int, index int, value int){
  arr = append(arr[:index], append([]int{value}, arr[index:]...)...)
}

This function takes an array of integers, an index, and a value, then inserts the value at the specified index. The first step is to append the value to the array at the position of the index. Next, append the remaining elements after the index to the newly appended element. Finally, assign the new array to the original array reference, thus inserting the new value into the array. This function modifies the original array reference and does not return a new array.

go