How to append an array to an array in Go

In this shot, we will learn to append an array to an array using Golang.

There is no way in Golang to directly append an array to an array. Instead, we can use slices to make it happen.

The following characteristics are important to note:

  • Arrays are of a fixed size.
  • We cannot allocate size to an array at runtime.

You may think of an approach where we create a new array with the size of both arrays and copy all the elements from both arrays to a new array using a for loop. However, Golang doesn’t support providing dynamic size at runtime to an array.

We can append two slices using the built-in function, append().

Syntax

newSlice = append(slice1, slice2...)

Parameters

The append() function takes two slices as parameters followed by ... at the end.

Return value

The append function returns a new slice by appending the slices passed to it.

Implementation

package main
//import fmt package
import(
"fmt"
)
//Program execution starts here
func main(){
//Declare and initialize slice1
slice1 := []int{10, 11}
//Declare and initialize slice2
slice2 := []int{12, 13}
//Append slice1 and slice2 and assign it to slice1
slice1 = append(slice1, slice2...)
//display new slice 1
fmt.Println(slice1)
}

Explanation

In the code snippet above:

  • Line 5: We import the fmt package.
  • Line 9: Program execution starts from main() function.
  • Line 12: We declare and initialize the first slice, slice1.
  • Line 15: We declare and initialize the second slice, slice2.
  • Line 18: We pass slice1 and slice2 as parameters to the append() function, and assign the returned slice to slice1. Here, we can assign it to a new slice too.
  • Line 21: We print the updated slice slice1, which contains elements from slice1 and slice2.

Free Resources