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:
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()
.
newSlice = append(slice1, slice2...)
The append()
function takes two slices as parameters followed by ...
at the end.
The append function returns a new slice by appending the slices passed to it.
package main//import fmt packageimport("fmt")//Program execution starts herefunc main(){//Declare and initialize slice1slice1 := []int{10, 11}//Declare and initialize slice2slice2 := []int{12, 13}//Append slice1 and slice2 and assign it to slice1slice1 = append(slice1, slice2...)//display new slice 1fmt.Println(slice1)}
In the code snippet above:
fmt
package.main()
function.slice1
.slice2
.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.slice1
, which contains elements from slice1
and slice2
.