Alex Garella
18th July 2023
Let's dive into one fundamental operation in Rust – concatenating vectors.
There are a few approaches to concatenate vectors in Rust, but three of them are commonly used:
Let's explore in detail what these methods do, what their difference are and what performance implications come with their usage.
The append()
function takes a mutable reference to a second vector vec2
and moves all of its elements to vec1
, leaving vector vec2
empty.
fn main() {
let mut vec1 = vec![1, 2, 3];
let mut vec2 = vec![4, 5, 6];
vec1.append(&mut vec2);
println!("vec1: {:?}", vec1);
println!("vec2: {:?}", vec2);
// Output:
//vec1: [1, 2, 3, 4, 5, 6]
//vec2: []
}
The extend()
function can be used if you want to keep the original vectors intact. extend() takes an iterator and appends all its elements to the caller vector.
fn main() {
let mut vec1 = vec![1, 2, 3];
let vec2 = vec![4, 5, 6];
vec1.extend(&vec2);
println!("vec1: {:?}", vec1);
println!("vec2: {:?}", vec2);
// Output:
// vec1: [1, 2, 3, 4, 5, 6]
// vec2: [4, 5, 6]
}
In the example above, vec2
remains unchanged after the operation.
The concat()
function concatenates an iterable of vectors into a new vector. The original vectors remain unchanged.
fn main() {
let vec1 = vec![1, 2, 3];
let vec2 = vec![4, 5, 6];
let vec3 = vec![vec1, vec2].concat();
println!("vec3: {:?}", vec3);
// Output:
// vec1: [1, 2, 3]
// vec2: [4, 5, 6]
// vec3: [1, 2, 3, 4, 5, 6]
}
Please note that concat()
only works on vectors with elements of type T that implement Copy.
The choice of method largely depends on your specific use case and whether you need to keep the original vectors intact.