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.
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:
The append() method returns a slice containing all the elements of the original slice plus the provided values.
The syntax –
func append(s []T, vs …T) []T
The first parameter, s, is a slice of type T, and the other parameters are T values to append to the 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"}
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
To convert an int to a string, Golang has a built-in package and methods. To…
in this post, We'll learn here about converting an int value to string in golang.…
in this post, we'll show you how to format strings in Golang. Golang has a…
in this tutorial, We'll learn how to use golang sleep in an application. We can…
in this tutorial, We'll split a string from a string using golang inbuilt method. The…
This Golang tutorial will show you how to make a CRUD operation API using the…