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]
In this example, we have three slices slice1, slice2, and slice3.
To concatenate them, we first append slice2 to the end of slice1 using the… operator to expand slice2 to individual elements.
Then, we appended slice3 to the resulting slice, concatenated. Finally, we print the concatenated slice using fmt.Println() function.
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.
Conclusion
You can use the append() function to concatenate two or more slices in Go. The append() function appends elements to the end of a slice and returns the resulting slice.

Krunal Lathiya is a Software Engineer with over eight years of experience. He has developed a strong foundation in computer science principles and a passion for problem-solving. In addition, Krunal has excellent knowledge of Distributed and cloud computing and is an expert in Go Language.