How to Merge Two Slices in Go

You can merge two slices in Go by creating a new slice with a capacity equal to the sum of both lengths, then using the built-in `append` function to copy elements from the first slice followed by the second.

You can merge two slices in Go by creating a new slice with a capacity equal to the sum of both lengths, then using the built-in append function to copy elements from the first slice followed by the second. This approach avoids manual loops and ensures efficient memory allocation.

Here is the most common pattern using append with the variadic spread operator (...):

package main

import "fmt"

func main() {
    slice1 := []int{1, 2, 3}
    slice2 := []int{4, 5, 6}

    // Pre-allocate capacity to avoid multiple reallocations
    merged := make([]int, 0, len(slice1)+len(slice2))
    merged = append(merged, slice1...)
    merged = append(merged, slice2...)

    fmt.Println(merged) // Output: [1 2 3 4 5 6]
}

If you prefer a one-liner, you can chain the append calls directly, though pre-allocating capacity (as shown above) is generally better for performance when dealing with large slices:

merged := append([]int(nil), slice1...)
merged = append(merged, slice2...)

Important Considerations:

  • Nil Slices: If either input slice is nil, append handles it gracefully without panicking.
  • Shared Memory: append copies the underlying data references. If your slices contain pointers or structs with pointers, the merged slice will reference the same underlying objects. Modifying those objects in the merged slice will affect the original slices.
  • In-Place Modification: If you are merging into an existing slice that has enough capacity, you can append directly to it. However, if you need a completely new slice to preserve the originals, always start with a new slice (like make([]T, 0, cap) or append([]T(nil), ...)).

For merging slices of different types or complex objects, the logic remains the same: create a new slice with the correct type and capacity, then append the source slices using the ... operator.