How to concatenate vectors using append() or extend() in Rust
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.
The append() method
The 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);}}
Code explanation
Let’s discuss the above code snippet in detail.
Lines 3–4: We use the
letandmutkeywords to declare the mutable vectors, such asmy_vec1andmy_vec2.Line 6: The
append()method takes the reference ofmy_vec2vector.Lines 8–12L: The
forloop is used to print the values ofmy_vec1that include values ofmy_vec2vector 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.
The extend() method
The 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);}}
Code explanation
Let’s discuss the code snippet above in more detail.
Lines 3–4: We use the
mutkeyword only withmy_vector1to make it mutable.Line 6: The
extend()method takesmy_vector2as a vector iterator. It iterates each element ofmy_vector2and appends them tomy_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