Vector Concatenation in Rust

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:

  1. append()
  2. extend()
  3. concat()

Let's explore in detail what these methods do, what their difference are and what performance implications come with their usage.

1. Using the append() Method

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: [] }

2. Using the extend() Method

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.

3. Using the concat() Method

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.

Performance Implications

  1. append(): Fastest as it does not require new memory allocations but it leaves the appended vector empty.
  2. extend(): Slower than append() since it has to reallocate the memory, but it leaves the original vectors intact.
  3. concat(): Similar to extend() but it works on an iterable of vectors. This makes it more convenient when you have more than two vectors.

The choice of method largely depends on your specific use case and whether you need to keep the original vectors intact.

Subscribe to receive the latest Rust jobs in your inbox

Receive a weekly overview of Rust jobs by subscribing to our mailing list

© 2024 RustJobs.dev, All rights reserved.