0
0
GoHow-ToBeginner · 3 min read

How to Merge Two Slices in Go: Simple Syntax and Example

In Go, you merge two slices using the append function by appending one slice to another with the syntax append(slice1, slice2...). The three dots ... unpack the second slice so its elements are added individually to the first slice.
📐

Syntax

The basic syntax to merge two slices slice1 and slice2 is:

  • append(slice1, slice2...): This appends all elements of slice2 to slice1.
  • The ... after slice2 is called the 'variadic' operator and it unpacks the slice elements.
go
mergedSlice := append(slice1, slice2...)
💻

Example

This example shows how to merge two slices of integers and print the result.

go
package main

import "fmt"

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

    mergedSlice := append(slice1, slice2...)

    fmt.Println("Merged slice:", mergedSlice)
}
Output
Merged slice: [1 2 3 4 5 6]
⚠️

Common Pitfalls

One common mistake is forgetting the ... after the second slice, which causes a compile error because append expects individual elements, not a slice.

Also, remember that append returns a new slice, so you must assign it to a variable.

go
package main

import "fmt"

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

    // Wrong: missing ... causes error
    // merged := append(slice1, slice2) // compile error

    // Correct way:
    merged := append(slice1, slice2...)
    fmt.Println(merged)
}
Output
[1 2 3 4]
📊

Quick Reference

Remember these tips when merging slices in Go:

  • Use append(slice1, slice2...) to merge.
  • The ... unpacks the second slice.
  • Assign the result of append to a variable.
  • Works with slices of any type.

Key Takeaways

Use append(slice1, slice2...) to merge two slices in Go.
The ... operator unpacks the second slice elements for appending.
Always assign the result of append to a variable to keep the merged slice.
Merging slices works with any slice type, not just integers.
Forgetting ... after the second slice causes a compile error.