How to concatenate two or more slices in Golang?


The append built-in function appends elements to the end of a slice. If it has sufficient capacity, the destination is re-sliced to accommodate the new elements. If it does not, a new underlying array will be allocated. Append returns the updated slice

Example

package main 

import "fmt" 
 
func main() {
	a := []int{1, 2, 3, 4, 5}
	b := []int{6, 7, 8, 9, 10}
	c := []int{11, 12, 13, 14, 15}
	
	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))
	
	fmt.Printf("c: %v\n", c)
	fmt.Printf("cap(c): %v\n", cap(c))
	
	x := []int{}
	x = append(a,b...)	// Can't concatenate more than 2 slice at once
	x = append(x,c...)	// concatenate x with c
	
	fmt.Printf("\n######### After Concatenation #########\n")
	fmt.Printf("x: %v\n", x)
	fmt.Printf("cap(x): %v\n", cap(x))
}

Output

a: [1 2 3 4 5]
cap(a): 5
b: [6 7 8 9 10]
cap(c): 5
c: [11 12 13 14 15]
cap(c): 5

######### After Concatenation #########
x: [1 2 3 4 5 6 7 8 9 10 11 12 13 14 15]
cap(x): 20
Most Helpful This Week