Concatenate two slices in Go
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
Concatenating two slices in Go is usually done with append, and that is the idiomatic answer most of the time. The only extra detail is whether you are okay with reusing the backing array of the first slice or whether you need a fresh independent result.
The Idiomatic Form
To append all elements of one slice onto another, use append with the variadic expansion operator:
Output:
The ... after b expands the second slice into individual arguments for append.
What append May Do Under the Hood
append may reuse the backing array of a if there is enough capacity. If not, it allocates a new array and copies the data.
That means concatenation can be efficient, but it also means result may share storage with a in some cases.
If shared storage is acceptable, append(a, b...) is the best default answer.
When You Need an Independent Result
If you do not want the result tied to the capacity behavior of a, allocate a fresh slice yourself:
This guarantees the result starts from a clean destination slice.
Manual Copy Is Also Valid
You can also concatenate with copy if you want precise control:
This is more verbose than append, but sometimes useful when you are already working with fixed destination sizing.
It also makes intent explicit: the result is a new slice with exact final length, not an extension of the first slice that may or may not reuse existing capacity. That can be easier to reason about in code that shares slices across package boundaries.
Concatenating in a Loop
If you are joining many slices, avoid repeated small reallocations by planning capacity up front:
That is often cleaner and faster than letting the slice grow unpredictably in a tight loop.
Common Pitfalls
The biggest mistake is forgetting the ... when appending a slice to another slice. Without it, append treats the second argument differently and the code will not compile for plain slice concatenation.
Another mistake is assuming append always allocates a new slice. It may reuse the backing array of the first slice, which matters if other code still references that data.
A third issue is building a result in a loop without reserving enough capacity. That can cause repeated reallocations and extra copying.
Summary
- The idiomatic way to concatenate two slices in Go is
append(a, b...). - Use a preallocated destination when you want a fresh independent result.
- '
copyis a valid lower-level alternative when you want explicit control.' - Remember that
appendmay reuse the backing array of the first slice. - Preallocate capacity when concatenating many slices in a loop.

