How to concatenate two slices in Golang?

Go ProgrammingServer Side ProgrammingProgramming

Whenever we talk about appending elements to a slice, we know that we need to use the append() function that takes a slice as the first argument and the values that we want to append as the next argument.

The syntax looks something like this.

sl = append(sl,1)

Instead of appending a single number to the slice "sl", we can append multiple values in the same command as well.

Consider the snippet shown below.

sl = append(sl,1,2,3,4)

The above code will work fine in Go.

When it comes to appending a slice to another slice, we need to use the variadic function signature dots. In variadic functions in Golang, we can pass a variable number of arguments to the function and all the numbers can be accessed with the help of the argument name.

Let's consider a simple example, where we will add multiple numbers to an integer slice.

Example 1

Consider the code shown below.

package main
import "fmt"
func main() {
   sl := []int{1, 2, 3}
   sl = append(sl, 5, 6, 7)
   fmt.Println(sl)
}

Output

When we run the code, it will produce the following output −

[1 2 3 5 6 7]

Now, let's suppose that instead of passing a number, we pass a slice literal as an argument to the append function.

It should be noted that, to pass a slice literal, we need to use the three dots (...).

Example 2

Consider the code shown below.

package main
import "fmt"
func main() {
   sl := []int{1, 2, 3}
   sl = append(sl, []int{4, 5}...)
   fmt.Println(sl)
}

Output

When we run the code, it will produce the following output −

[1 2 3 4 5]

We can also pass a slice instead of passing a slice literal as shown in the above example.

Example 3

Consider the code shown below.

package main
import "fmt"
func main() {
   sl := []int{1, 2, 3}
   sl = append(sl, 5, 6, 7)
   sl1 := []int{0}
   sl1 = append(sl1, sl...)
   fmt.Println(sl)
   fmt.Println(sl1)
}

Output

When we run the code, it will produce the following output −

[1 2 3 5 6 7]
[0 1 2 3 5 6 7]
raja
Updated on 22-Feb-2022 05:43:33

Advertisements