Rust Vector Concatenation Guide
Rust Vectors: Exercise-8 with Solution
Write a Rust program to create two vectors: one with integers 1 to 5 and another with integers 6 to 10. Concatenate the two vectors and print the resulting vector.
Sample Solution:
Rust Code:
// Define the main function, the entry point of the program
fn main() {
// Create the first vector with integers 1 to 5
let vec1: Vec<i32> = (1..=5).collect(); // Use the range and collect method to create the vector
// Create the second vector with integers 6 to 10
let vec2: Vec<i32> = (6..=10).collect(); // Use the range and collect method to create the vector
// Concatenate vec1 and vec2 into a new vector
let concatenated_vec = [vec1, vec2].concat(); // Use the concat method for slices
// Print the resulting concatenated vector
println!("Concatenated Vector: {:?}", concatenated_vec);
}
Output:
Concatenated Vector: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Explanation:
Here is a brief explanation of the above Rust code:
- The main function (fn main()) is defined as the starting point of the Rust program.
- Two vectors, 'vec1' and 'vec2', are created using the range syntax (1..=5) and (6..=10) respectively, which are then collected into vectors using the ".collect()" method. The type Vec<i32> explicitly states that these vectors contain 32-bit integers.
- The 'concatenated_vec' is created by concatenating 'vec1' and 'vec2' using the ".concat()" method. The [vec1, vec2] is a slice of vectors that are concatenated into a single vector. This operation does not modify 'vec1' or 'vec2'; instead, it creates a new vector that contains all the elements of 'vec1' followed by all the elements of 'vec2'.
- Finally, the concatenated vector is printed to the console using the "println!" macro with {:?} placeholder for debug formatting, which displays the vector's contents.
Rust Code Editor:
Previous: Rust Vector Mapping guide.
Next: Rust File Operations: Copy, Move, Delete with Error handling.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/rust/collections_and_data_structures/rust-vectors-exercise-8.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics