Is it even possible to concatenate vectors in Rust? If so, is there an elegant way to do so? 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 of a better way?
Is it even possible to concatenate vectors in Rust? If so, is there an elegant way to do so? 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 of a better way?
The structure
std::vec::Vec
has methodappend()
:From your example, the following code will concatenate two vectors by mutating
a
andb
:Alternatively, you can use
Extend::extend()
to append all elements of something that can be turned into an iterator (likeVec
) to a given vector:Note that the vector
b
is moved instead of emptied. If your vectors contain elements that implementCopy
, you can pass an immutable reference to one vector toextend()
instead in order to avoid the move. In that case the vectorb
is not changed: