Concat
Suppose we have 2 slices (or more) and want to combine them together into a single slice. We can use the slices.Concat
generic func
, part of "slices," for this.
While it is possible to use append()
and a for
-loop to merge 2 slices, slices.Concat
does this work for us. It can lead to cleaner Go code that is easier to read and maintain.
This program creates multiple slices of varying types, and then uses slices.Concat
on them. It even uses a slice of any values, which can have multiple types.
slices.Concat
on 2 string
slices. The resulting slice has 5 elements in their original order.slices.Concat
function can merge 3 slices together in a single call. Even more arguments could be passed to Concat
.slices.Concat
works as expected with any types.package main
import (
"fmt"
"slices"
)
func main() {
// Part 1: use Concat to combine 2 slices of the same types together.
slice1 := []string{"bird", "frog", "dog"}
slice2 := []string{"carrot", "onion"}
sliceMerged := slices.Concat(slice1, slice2)
fmt.Println(len(sliceMerged), sliceMerged)
// Part 2: combine 3 slices together with Concat.
slice3 := []int{100, 50}
slice4 := []int{0}
slice5 := []int{500, 1000}
sliceMerged2 := slices.Concat(slice3, slice4, slice5)
fmt.Println(len(sliceMerged2), sliceMerged2)
// Part 3: use slices.Concat on arrays of any type.
slice6 := []any{"bird", "cat"}
slice7 := []any{10, 20}
sliceMerged3 := slices.Concat(slice6, slice7)
fmt.Println(len(sliceMerged3), sliceMerged3)
}5 [bird frog dog carrot onion]
5 [100 50 0 500 1000]
4 [bird cat 10 20]
The "slices" package contains many helpful functions for handling slices. The functions are generic, which means they can be used on slices with all different element types.