w3resource

Rust vector filtering guide

Rust Vectors: Exercise-6 with Solution

Write a Rust program to create a vector with integers from 1 to 10. Filter out even numbers 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 10
    let numbers: Vec<i32> = (1..=10).collect(); // Use the collect() method to create a vector from a range

    // Filter out odd numbers and collect the result into a new vector
    let even_numbers: Vec<i32> = numbers.into_iter() // Convert the vector into an iterator
        .filter(|&x| x % 2 == 0) // Use the filter method to keep only even numbers
        .collect(); // Collect the filtered elements back into a vector

    // Print the resulting vector with even numbers
    println!("Even numbers: {:?}", even_numbers);
}

Output:

Even numbers: [2, 4, 6, 8, 10]

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 numbers: Vec<i32> = (1..=10).collect();: This line creates a vector named numbers containing integers from 1 to 10 using the "collect()" method with a range (1..=10).
  • let even_numbers: Vec<i32> = numbers.into_iter(): This line starts the process of filtering out odd numbers by converting the 'numbers' vector into an iterator. The "into_iter()" method consumes the 'numbers' vector, allowing for iteration over its elements.
  • .filter(|&x| x % 2 0): This line filters the elements of the iterator, keeping only those elements 'x' for which x % 2 0 is true (i.e., even numbers).
  • .collect();: This line collects the filtered elements back into a new vector named 'even_numbers'.
  • println!("Even numbers: {:?}", even_numbers);: This line prints the 'even_numbers' vector to the console. The {:?} syntax is used for debug formatting, which is suitable for printing the contents of collections like vectors.

Rust Code Editor:

Previous: Rust Vector sorting guide.
Next: Rust Vector Mapping 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://w3resource.com/rust/collections_and_data_structures/rust-vectors-exercise-6.php