OneBite.Dev - Coding blog in a bite size

merge two arrays in Go

Code snippet on how to merge two arrays in Go

package main

import "fmt"

func main() {
    arrayA := []int{1, 2, 3, 4, 5}
    arrayB := []int{6, 7, 8, 9, 10}
    
    arrayC := make([]int, len(arrayA) + len(arrayB))
    
    for i, v := range arrayA {
        arrayC[i] = v
    }
    
    for i, v := range arrayB {
        arrayC[i + len(arrayA)] = v
    }
    
    fmt.Printf("Merged arrayC: %v\n", arrayC)
}

This code uses Go to merge two arrays, arrayA and arrayB, into a new array, arrayC. In the code, the length of both arrays is counted and stored in a variable. Then, the elements in both arrays are looped over, assigning the values of arrayA to the beginning part of arrayC and the values of arrayB to the end. After the looping is complete, the merged arrayC is printed.

go