golang tutorials

Merge Two or More Slices in Golang

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
Brad

Recent Posts

How to convert an int value to string in Go?

To convert an int to a string, Golang has a built-in package and methods. To…

5 months ago

Convert Int to a String in Golang

in this post, We'll learn here about converting an int value to string in golang.…

5 months ago

How To Format a String in Golang

in this post, we'll show you how to format strings in Golang. Golang has a…

5 months ago

How To Halt Execution in Golang Using Sleep

in this tutorial, We'll learn how to use golang sleep in an application. We can…

5 months ago

Split String From a String in Golang

in this tutorial, We'll split a string from a string using golang inbuilt method. The…

6 months ago

Golang CRUD Rest API with Echo

This Golang tutorial will show you how to make a CRUD operation API using the…

6 months ago