How to insert an element into an array at a specific index in Golang 1.20
In this video we are going to generate source code for the GoLang Program, How to insert an element into an array at a specific index in using chatGPT.
After generating we will verify and run the generated code.
IMPORTANT NOTE on SOURCE CODE: only source code that are acceptable by the youtube description box will be displayed.
In this program I have replaced the angled brackets with > or <. once you copy the source code to editor replace it with greater than or less than symbols respectively.
##############SOURCE CODE#########################
package main
import "fmt"
func main() {
// create an array
arr := [5]int{1, 2, 3, 4, 5}
// print the original array
fmt.Println("Original array:", arr)
// insert an element at index 2
insertElement(&arr, 2, 10)
// print the modified array
fmt.Println("Modified array:", arr)
}
func insertElement(arr *[5]int, index int, element int) {
// shift elements to the right from index position
for i := len(arr) - 1; i > index; i-- {
arr[i] = arr[i-1]
}
// insert the new element at index position
arr[index] = element
}
##############END OF SOURCE CODE#########################
Below is the explanation for the program:
The program first creates an array arr with 5 elements. It then prints the original array using fmt.Println().
The insertElement() function is then called to insert an element at index 2 with a value of 10.
The insertElement() function takes a pointer to the original array as its first argument so that it can modify the original array directly.
The insertElement() function shifts all the elements to the right of the index position one position to the right.
This makes room for the new element to be inserted at the index position. Finally, the new element is inserted at the index position.
The modified array is then printed using fmt.Println() to verify that the insertion was successful.
#go #goprogramming #golang #golangtutorial #golanguage