How to concatenate two vectors?

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 !

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 Likes

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

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();
17 Likes

Nice ! That's even greater !

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.

2 Likes

just did it
[&self[..], &[String::from("Bar")]].concat()
that's it

1 Like