How to Append an Array to Array in Golang

There is no way in Golang to append an array to an array directly, but you can use the slice and append a slice to another slice.

In Go, you can “append one array (or slice) to another using the append() function along with the variadic … syntax.” The append() function works with slices, so if you are working with arrays, you must first convert them to slices.

Syntax

new_slice = 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.

Example 1

package main

import (
  "fmt"
)

func main() {
  // Creating and initializing two slices
  slice1 := []int{1, 2, 3}
  slice2 := []int{4, 5, 6}

  // Appending slice2 to slice1
  result := append(slice1, slice2...)

  // Displaying the result
  fmt.Println("Original Slice 1:", slice1)
  fmt.Println("Original Slice 2:", slice2)
  fmt.Println("Appended Result:", result)
}

Output

[10 11 12 13]

The append(slice1, slice2…) line is key here.

The syntax spreads the elements of slice2 so that they can be appended individually to slice1.

If you are working with arrays, you can create slices from them using slicing syntax like array1[:].

Example 2

package main

import (
  "fmt"
)

// Function to merge two slices of integers
func mergeIntSlices(slice1, slice2 []int) []int {
  return append(slice1, slice2...)
}

// Function to merge two slices of strings
func mergeStringSlices(slice1, slice2 []string) []string {
  return append(slice1, slice2...)
}

func main() {
  // Initializing slices of integers
  intSlice1 := []int{10, 20, 30}
  intSlice2 := []int{40, 50}

  // Initializing slices of strings
  stringSlice1 := []string{"apple", "banana"}
  stringSlice2 := []string{"cherry", "date", "elderberry"}

  // Merging integer slices
  mergedIntSlice := mergeIntSlices(intSlice1, intSlice2)
  fmt.Println("Merged Integer Slice:", mergedIntSlice)

  // Merging string slices
  mergedStringSlice := mergeStringSlices(stringSlice1, stringSlice2)
  fmt.Println("Merged String Slice:", mergedStringSlice)

  // Appending another integer to the merged integer slice
  mergedIntSlice = append(mergedIntSlice, 60)
  fmt.Println("Merged Integer Slice (after appending 60):", mergedIntSlice)

  // Appending another string slice to the merged string slice
  extraStringSlice := []string{"fig", "grape"}
  mergedStringSlice = append(mergedStringSlice, extraStringSlice...)
  fmt.Println("Merged String Slice (after appending more):", mergedStringSlice)
}

Output

Append an Array to Array in Go

This code demonstrates how to merge slices of different types and lengths using custom functions and the built-in append() function. It also illustrates how you can continue appending to a merged slice.

That’s it!

Related posts

Delete an Element from a Slice in Golang

Concatenate Two or More Slices in Golang

Leave a Comment