Golang Program to insert an element into the array at the specified index


In this tutorial, we will write a go language program to insert an element into an array at the specified index. There are many methods to add elements to an array. it can be done by either using indexing or by using for loops. There are some inbuilt functions too using which we can add elements at the specified indexes.

Syntax

func make ([] type, size, capacity)

The make function in go language is used to create an array/map it accepts the type of variable to be created, its size and capacity as arguments

func append(slice, element_1, element_2…, element_N) []T

The append function is used to add values to an array slice. It takes number of arguments. The first argument is the array to which we wish to add the values followed by the values to add. The function then returns the final slice of array containing all the values.

Algorithm

STEP 1 − First, we need to import the fmt package.

STEP 2 − Now, we need to start the main() function.

STEP 3 − Here, initialize an array of integers using make() function and append values to the array using append() function. further print the array on the screen by using fmt.Println() function.

STEP 4 − Store the index of element in a variable that should be changed. Now by using name_of_array[index] notation change the element present at that location to the new value.

STEP 5 − Further, print the new array thus formed on the screen using fmt.Println() function.

Example

In this example we will write a go language program to add an element into an array at specified index using the concept of indexing in arrays.

package main
import "fmt"
func main() {

   // initializing array
   array := make([]int, 0, 8)
   array = append(array, 11, 20, 13, 44, 56, 96, 54, 97)
   fmt.Println("The given array is:", array)

   // getting the index
   var index int = 4
   array[index] = 65
   fmt.Println()
   fmt.Println("The new array obtained after changing the element at", index, "index is:", array)
}

Output

The given array is: [11 20 13 44 56 96 54 97]

The new array obtained after changing the element at 4 index is: [11 20 13 44 65 96 54 97]

Conclusion

We have successfully compiled and executed a go language program to add elements into an array at specified index along with examples. we have created two programs here in the first program we have used the concept of indexing to add element at a particular index while in the second examples we have used a different array to append values to an array.

Updated on: 09-Feb-2023

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements