How to concatenate two vectors?


#1

Hello,

I’m trying to concatenate two vectors. The obvious way to do that is iterating over the second vector and use push on the first one to add each element of the second.

There is also an append function that concat the second vector in the first one, but for unknown reason (to me) it empties the second one.

What’s the idiomatic way to do that in Rust ?

Many thanks !


#2

If you want to keep the second vector around after the concatenation, you can do first.extend(second.iter().cloned()) to clone each element from the second and insert it into the first.


#3

Thanks for your reply, I missed this one while browsing the doc !


#4

first.extend(&second) also works (Vec has a second extend implementation for iterables over &T) :slight_smile:

There’s also concat method on slices of slices:

let concatenated = [&first[..], &second[..]].concat();

#5

Nice ! That’s even greater !


#6

Because it moves all the elements from one vector to another. Transferring ownership requires that the element exists in only one place. Append is a very efficient operation, regardless of the element type; the elements don’t even need to implement Clone to be moved from one vector to another.