OneBite.Dev - Coding blog in a bite size

append item in array in Go

Code snippet on how to append item in array in Go

  arr := []int{1, 2, 3, 4}
  n := 5
  // append n to the end of the array
  arr = append(arr, n)

This code will append the number 5 to the end of an array called arr that is initially composed of the four numbers 1, 2, 3, and 4.

First, we declare the variable arr as a slice of integers and initialise it to contain the four numbers 1, 2, 3, and 4. We also declare another variable n and assign it the value 5.

Next, the append() function is used to add the value of n to the end of arr. The append() function takes two arguments: the original slice and the item to append. The result of the append() call is another slice, which is assigned back to the arr variable.

Now, if you inspect the value of arr, it will have the five numbers 1, 2, 3, 4, and 5.

go