OneBite.Dev - Coding blog in a bite size

insert an element at the beginning of an array in Go

Code snippet on how to insert an element at the beginning of an array in Go

// Initialize an array of strings
arr := []string{"apple", "banana", "cherry"}

// Declare a new element to be inserted
ele := "date"

// Copy the contents of the original array to the destination
copy(arr[1:], arr[:])

// Insert the element at the beginning of the array
arr[0] = ele

fmt.Println(arr)  // Output: [date apple banana cherry]

This code creates an array arr and a new element ele. To insert ele at the beginning of the arr, the values of arr need to be shifted to the right by one. To do this, the contents of the original array are copied to the destination by using the copy function. Finally, the element ele is inserted at the beginning of the array, and the resulting array is printed.

go