Apps Artificial Intelligence CSS DevOps Go JavaScript Laravel Linux MongoDB MySQL PHP Python Rust Svelte Vue

Practical Ways to Combine Slices in Go

1 min read .
Practical Ways to Combine Slices in Go

Combining slices is common when data comes from several sources or processing stages. In Go, the standard approach is append, optionally with preallocated capacity when the final size is known.

1. Combine Slices with append

package main

import "fmt"

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

	combined := append(slice1, slice2...)
	combined = append(combined, slice3...)

	fmt.Println(combined)
}

Output:

[1 2 3 4 5 6 7 8 9]

The ... syntax passes the elements of the second slice to the variadic append function.

One important detail: append(slice1, ...) may reuse slice1’s backing array. If the original slices must remain isolated from future mutations, build the result in a separate allocation.

2. Preallocate Capacity

If you know the final length, preallocate capacity to reduce reallocations:

package main

import "fmt"

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

	totalLen := len(slice1) + len(slice2) + len(slice3)
	combined := make([]int, 0, totalLen)

	combined = append(combined, slice1...)
	combined = append(combined, slice2...)
	combined = append(combined, slice3...)

	fmt.Println(combined)
}

This also guarantees that combined has its own backing storage from the start.

3. Combine a Dynamic Number of Slices

When the number of input slices varies, loop over them:

package main

import "fmt"

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

	totalLen := 0
	for _, s := range slices {
		totalLen += len(s)
	}

	combined := make([]int, 0, totalLen)
	for _, s := range slices {
		combined = append(combined, s...)
	}

	fmt.Println(combined)
}

Conclusion

Use append for simple concatenation, preallocate when you know the combined size, and loop when the number of source slices is dynamic. When aliasing matters, remember that slices may share an underlying array unless you deliberately allocate a separate result.

Related Posts

chevron-up