insert an element into an array at a specific index in go

To insert an element into a specific index of an array in Go, we need to shift the elements after the index to the right and insert the new element in the index. Here's one way to do it:

main.go
func insertElement(arr []int, index int, element int) []int {
    arr = append(arr, 0)         // Step 1: Add a new element to the end
    copy(arr[index+1:], arr[index:]) // Step 2: Shift the elements after index to the right
    arr[index] = element         // Step 3: Insert the new element at the index
    return arr
}
324 chars
7 lines

Here's how we can use the function to insert an element:

main.go
arr := []int{1, 2, 3, 4, 5}
index := 2 // Index to insert the element
element := 10 // New element to be inserted
arr = insertElement(arr, index, element)
fmt.Println(arr) // Output: [1 2 10 3 4 5]
198 chars
6 lines

In this example, we're inserting 10 at index 2 of the array [1, 2, 3, 4, 5]. The resulting array is [1, 2, 10, 3, 4, 5].

gistlibby LogSnag