How to Concatenate Two or More Slices in Golang

To concatenate two or more slices in Golang, you can use the “append()” function. For example, if you have two slices, s1, and s2, you can concatenate them using s3:= append(s1, s2…), where the  operator is used to unpack the elements of s2 into individual arguments for the append() function.

Example 1

package main

import "fmt"

func main() {
  slice1 := []int{1, 2, 3}
  slice2 := []int{4, 5, 6}
  slice3 := []int{7, 8, 9}

  // Concatenate slices
  concatenated_slices := append(slice1, slice2...)
  concatenated_slices = append(concatenated_slices, slice3...)

 fmt.Println(concatenated_slices)
}

Output

[1 2 3 4 5 6 7 8 9]

Example 2

To concatenate slices of different types, you can use the generic “concatSlice()” function if you use Go v1.18 or later.

package main

import "fmt"

func concatSlice[T any](slices ...[]T) []T {
  var result []T
  for _, s := range slices {
    result = append(result, s...)
  }
 return result
}

func main() {
  slice1 := []string{"a", "b"}
  slice2 := []string{"c", "d"}

  s3 := concatSlice(slice1, slice2)
  fmt.Println(s3)
}

Output

[a b c d]

Side effects of append() function

One possible side effect of slice concatenation with append() is that it may modify the underlying array of the first slice if it has enough capacity to hold the elements from the second slice. This means that the concatenated slice will share the same memory as the first slice, and any changes to one will affect the other.

package main

import "fmt"

func main() {
  s1 := make([]int, 2, 4)
  s1[0] = 1
  s1[1] = 2
  s2 := []int{3, 4}
  s3 := append(s1, s2...)
  fmt.Println(s3)
  s3[0] = 9
  fmt.Println(s1)
}

Output

[1 2 3 4]
[9 2]

To avoid this side effect, you can either create a new slice with enough capacity and copy the elements from both slices into it or use a generic concatSlice() function using Go v1.18 or later.

That’s it!

Related posts

How to Append a Slice in Go

How to Delete an Element from a Slice in Go