w3resource

Rust Vector Operations Guide

Rust Vectors: Exercise-2 with Solution

Write a Rust program to create a vector with integers 1 to 5. Then, append integers 6 to 10 to the vector. Finally, remove the last element from the vector and print the resulting vector.

Sample Solution:

Rust Code:

// Define the main function
fn main() {
    // Create a vector with integers 1 to 5
    let mut numbers: Vec<i32> = (1..=5).collect(); // Use the collect() method to create a vector from a range

    // Append integers 6 to 10 to the vector
    for i in 6..=10 {
        numbers.push(i); // Append the current value of i to the vector
    }

    // Remove the last element from the vector
    numbers.pop(); // Use the pop() method to remove the last element

    // Print the resulting vector
    println!("The resulting vector is: {:?}", numbers);
}

Output:

The resulting vector is: [1, 2, 3, 4, 5, 6, 7, 8, 9]

Explanation:

Here is a brief explanation of the above Rust code:

  • fn main() {: This line defines the main function, which is the entry point of the program.
  • let mut numbers: Vec<i32> = (1..=5).collect();: This line creates a mutable vector "numbers" containing integers from 1 to 5 using the "collect()" method with a range (1..=5).
  • for i in 6..=10 {: This line starts a for loop that iterates from 6 to 10 (inclusive).
  • numbers.push(i);: Inside the loop, each integer i from 6 to 10 is appended to the vector using the "push()" method.
  • numbers.pop();: After appending integers 6 to 10, the "pop()" method is used to remove the last element from the vector.
  • println!("The resulting vector is: {:?}", numbers);: Finally, the resulting vector is printed using the "println" macro with the {:?} format specifier to display the contents of the vector.

Rust Code Editor:

Previous: Rust Vector Initialization Guide.
Next: Rust Vector access guide.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

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-2.php