Best Way to Concatenate Vectors in Rust

Is it even possible to concatenate vectors in Rust? If so, is there an elegant way to do this? I have something like this:

let mut a = vec![1, 2, 3]; let b = vec![4, 5, 6]; for val in &b { a.push(val); } 

Does anyone know a better way?

+28
vector concatenation rust
source share
2 answers

The std::vec::Vec structure has an append() method:

 fn append(&mut self, other: &mut Vec<T>) 

Moves all other elements to Self , leaving other empty.

In your example, the following code combines two vectors with mutating a and b :

 fn main() { let mut a = vec![1, 2, 3]; let mut b = vec![4, 5, 6]; a.append(&mut b); assert_eq!(a, [1, 2, 3, 4, 5, 6]); assert_eq!(b, []); } 

Alternatively, you can use Extend::extend() to add all the elements of what can be turned into an iterator (like Vec ) so that the given vector is:

 let mut a = vec![1, 2, 3]; let b = vec![4, 5, 6]; a.extend(b); assert_eq!(a, [1, 2, 3, 4, 5, 6]); // b is moved and can't be used anymore 

Note that the vector b moving, not empty. If your vectors contain elements that implement Copy , you can pass an immutable link to one vector to extend() instead to avoid moving. In this case, vector b does not change:

 let mut a = vec![1, 2, 3]; let b = vec![4, 5, 6]; a.extend(&b); assert_eq!(a, [1, 2, 3, 4, 5, 6]); assert_eq!(b, [4, 5, 6]); 
+40
source share

I can not do this on one line. Damian Dzyaduch

This can be done in one line using chain() :

 let c: Vec<i32> = a.into_iter().chain(b.into_iter()).collect(); // Consumed let c: Vec<&i32> = a.iter().chain(b.iter()).collect(); // Referenced let c: Vec<i32> = a.iter().cloned().chain(b.iter().cloned()).collect(); // Cloned let c: Vec<i32> = a.iter().copied().chain(b.iter().copied()).collect(); // Copied 

There are endless ways.

+2
source share

All Articles