Skip to content

How to Merge Two Slices in Golang?

Append function in Golang uses the Variadic function then you can use three dots to spread your slice:

func append(slice []Type, elems ...Type) []Type

A simple example to concatenate (merge or append) two slices:

package main

import "fmt"

func main() {
	firstSlice := []int{1, 2, 3}
	secondSlice := []int{4, 5, 6}

	mergedSlice := append(firstSlice, secondSlice...)

	fmt.Println(mergedSlice)
}

On the fly slice example:

package main

import "fmt"

func main() {
	baseSlice := []int{1, 2, 3}

	mergedSlice := append(baseSlice, []int{4, 5, 6}...)

	fmt.Println(mergedSlice)
}

Leave a Reply

Your email address will not be published. Required fields are marked *