How to Concatenate Two Slices in Go

Created
Modified

Using append Function

The append built-in function appends elements to the end of a slice.

You can use append function, it really simple. For example,

package main

import "fmt"

func main() {
  s1 := []string{"a", "b"}
  s2 := []string{"a", "c"}

  // slice = append(slice, anotherSlice...)
  s := append(s1, s2...)
  fmt.Printf("%q\n", s)

  // slice = append(slice, elem1, elem2)
  s = append(s1, s2[0], s2[1])
  fmt.Printf("%q\n", s)
}
["a" "b" "a" "c"]
["a" "b" "a" "c"]

Using Full Slice Expression

You can use a full slice expression which has the form a[low : high : max], which constructs a slice and also controls the resulting slice's capacity by setting it to max - low. The following example:

package main

import "fmt"

// For generics (if using 1.18 or later)
func concat[T any](s1 []T, s2 []T) []T {
  n := len(s1)
  return append(s1[:n:n], s2...)
}

func main() {
  s1 := []string{"a", "b"}
  s2 := []string{"a", "c"}

  s := append(s1[:2:2], s2...)
  fmt.Printf("%q\n", s)

  s = concat(s1, s2)
  fmt.Printf("%q\n", s)
}
["a" "b" "a" "c"]
["a" "b" "a" "c"]

Related Tags