This tutorial explains how to merge slice in Golang. New elements can be added to a slice. To attach new elements to the slice, Golang includes the append() method. This method returns the updated slice.
The documentation of the built-in package describes append.
What’s append Method
Appends elements to the end of a slice using the built-in append function. The destination is resliced to accommodate the new elements if it has enough capacity. A new underlying array will be allocated if it does not. The updated slice is returned by append. As a result, the result of append must be stored, often in the variable that holds the slice itself:
Concatenate Two or More Slices in Golang
The append() method returns a slice containing all the elements of the original slice plus the provided values.
Syntax append()
The syntax –
func append(s []T, vs …T) []T
Whereas –
The first parameter, s, is a slice of type T, and the other parameters are T values to append to the slice.
How To Initialize and declare Slice
We can declare and initialize slice using a single statement as like below –
s1 := []int{3, 4, 6, 8, 12}
s2 := []string{"go", "learn", "example"}
Merge Two Slice in Golang
Let’s create a golang code that’ll merge two slices and return a resulted slices that ll have both slice elements.
package main
import "fmt"
func main() {
a := []int{1, 12, 33, 44, 45}
b := []int{10, 19, 18, 94, 50}
fmt.Printf("a: %v\n", a)
fmt.Printf("cap(a): %v\n", cap(a))
fmt.Printf("b: %v\n", b)
fmt.Printf("cap(c): %v\n", cap(b))
x := []int{}
x = append(a,b...)
fmt.Printf("\n######### After Concatenation #########\n")
fmt.Printf("x: %v\n", x)
fmt.Printf("cap(x): %v\n", cap(x))
}
Output:
a: [1 12 33 44 45] cap(a): 5 b: [10 19 18 94 50] cap(c): 5 ######### After Concatenation ######### x: [1 12 33 44 45 10 19 18 94 50] cap(x): 10
