OneBite.Dev - Coding blog in a bite size

merge multiple array in Go

Code snippet on how to merge multiple array in Go

  package main

import (
	"fmt"
)

func main() {
	arr1 := []int{1, 2, 3, 4, 5}
	arr2 := []int{6, 7, 8, 9}
	
	// Initialize empty slice
	arr3 := []int{}
	
	// Loop through both array and append
	// each element of both array to arr3
	for _, value := range arr1 {
		arr3 = append(arr3, value)
	}
	
	for _, value := range arr2 {
		arr3 = append(arr3, value)
	}
	
	fmt.Println("Final merged array: ", arr3)

}

This code merges two arrays in Go. First, two arrays - arr1 and arr2 are declared. arr1 contains elements 1, 2, 3, 4, 5; arr2 contains elements 6, 7, 8, 9. Then, arr3 is initialized as an empty slice. arr1 and arr2 elements are looped over and appended to arr3. Finally, “Final merged array” is printed with the elements from both arr1 and arr2.

go