Concatenating Vectors in Rust

Authors

Rust is a statically-typed, compiled programming language that is designed to be fast, safe, and concurrent.

One common operation in Rust is concatenating two vectors, which combines the elements of two vectors into a single vector.

There are a few different ways to concatenate vectors in Rust.

How To Concatenate Vectors In Rust

.extend() Method

The most straightforward way is to use the .extend() method, which allows you to append the elements of one vector to another.

Here's an example:

let mut v1 = vec![1, 2, 3];
let v2 = vec![4, 5, 6];

v1.extend(v2);

assert_eq!(v1, [1, 2, 3, 4, 5, 6]);

.push() Method

Alternatively, you can use the .push() method to add individual elements from one vector to another.

This is useful if you only want to add a few elements from one vector to another, rather than the entire vector.

Here's an example:

let mut v1 = vec![1, 2, 3];
let v2 = vec![4, 5, 6];

for element in v2 {
    v1.push(element);
}

assert_eq!(v1, [1, 2, 3, 4, 5, 6]);

.into_iter() Method

If you want to concatenate two vectors and create a new vector as the result, you can use the .into_iter() method to iterate over the elements of the vectors and collect them into a new vector using the .collect() method.

Here's an example:

let v1 = vec![1, 2, 3];
let v2 = vec![4, 5, 6];

let v3: Vec<i32> = v1.into_iter().chain(v2.into_iter()).collect();

assert_eq!(v3, [1, 2, 3, 4, 5, 6]);

[a, b, c].concat() Method

Finally, you can also use the [a, b, c].concat() method to concatenate two vectors.

This method returns a new vector that contains the elements of both vectors in the order that they appear.

Here's an example:

let v1 = vec![1, 2, 3];
let v2 = vec![4, 5, 6];

let v3 = [v1, v2].concat();

assert_eq!(v3, [1, 2, 3, 4, 5, 6]);

Summary

In summary, there are several ways to concatenate vectors in Rust, depending on your specific needs.

Whether you want to append the elements of one vector to another, create a new vector by combining the elements of two vectors, or add individual elements from one vector to another, Rust provides a range of options to help you achieve your goals.

TrackingJoy