Vectors in the Rust programming language usually refer to dynamic arrays that allow us to store data with the same data type and insert new elements at runtime. The concatenation of these vectors helps us in combining and transforming data within Rust programs. In this Answer, we’ll discuss two methods, append()
and extend()
, to concatenate vectors in Rust.
append()
methodThe append()
method allows us to append the second vector to the first one. After performing this operation, the first vector contains elements of the second vector at the end, and the second vector becomes empty.
The syntax for the append()
method is given below:
vec1.append(&mut vec2)
The append()
method takes the &
with vec2
. Let’s see how it works in the example given below:
fn main() {let mut my_vec1 = vec![9,8,7,6];let mut my_vec2 = vec![55,44,33,22];my_vec1.append(&mut my_vec2);print!("my_vector1 : ");for i in my_vec1{print!("{} ",i);}}
Let’s discuss the above code snippet in detail.
Lines 3–4: We use the let
and mut
keywords to declare the mutable vectors, such as my_vec1
and my_vec2
.
Line 6: The append()
method takes the reference of my_vec2
vector.
Lines 8–12L: The for
loop is used to print the values of my_vec1
that include values of my_vec2
vector as well.
As we’ve seen, the append()
method concatenates vectors in place. Now, let’s move on to the next method that concatenates the vectors without taking the mutable references of another vector.
extend()
methodThe extend()
method concatenates vectors directly, taking an iterable vector rather than a reference to a vector. This method copies all elements to the first vector and appends them in the order they appear in the second vector. The good thing about the extend()
method is that it doesn’t empty the second vector.
The syntax for the extend()
method is given below:
vec1.extend(iterable)
The extend()
method takes the second vector as an argument and updates the first vector. Let’s see how it works in the example given below:
fn main() {let mut my_vector1 = vec![9,8,7,6];let my_vector2 = vec![5,4,3,2];my_vector1.extend(my_vector2);print!("my_vector1 : ");for i in my_vector1{print!("{} ",i);}}
Let’s discuss the code snippet above in more detail.
Lines 3–4: We use the mut
keyword only with my_vector1
to make it mutable.
Line 6: The extend()
method takes my_vector2
as a vector iterator. It iterates each element of my_vector2
and appends them to my_vector1
.
Let’s summarize both approaches by seeing their differences, as shown in the table below:
The | The | |
Description | Moves the second vector to the first vector | Appends the elements of second vector to the first vector |
Usecase | Doesn’t need a second vector | Needs a second vector |
Usage |
|
|
Free Resources