Home
Go
slices.Concat: Combine Two Slices
Updated Dec 29, 2024
Dot Net Perls
Slices, 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.
slices.Contains
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.
Example. 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.
Part 1 We use slices.Concat on 2 string slices. The resulting slice has 5 elements in their original order.
Part 2 The slices.Concat function can merge 3 slices together in a single call. Even more arguments could be passed to Concat.
Part 3 The "any" type can represent any type. We can use strings or ints for "any" elements. And 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]
Summary. 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.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Dec 29, 2024 (new).
Home
Changes
© 2007-2025 Sam Allen