Rust Vector Filtering & Slicing
Rust Vectors, Arrays, and Slices: Exercise-4 with Solution
Write a Rust program that creates a vector of integers containing both even and odd numbers. Filter out the even numbers from the vector and slice it to get a sub-vector containing the first 5 odd numbers. Print the sub-vector.
Sample Solution:
Rust Code:
fn main() {
// Create a vector of integers containing both even and odd numbers
let numbers: Vec<i32> = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// Filter out the even numbers from the vector
let odd_numbers: Vec<i32> = numbers.into_iter().filter(|&x| x % 2 != 0).collect();
// Slice the vector to get a sub-vector containing the first 5 odd numbers
let sub_vector = &odd_numbers[0..5];
// Print the resulting sub-vector
println!("Sub-Vector of First 5 Odd Numbers: {:?}", sub_vector);
}
Output:
Sub-Vector of First 5 Odd Numbers: [1, 3, 5, 7, 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 Rust program.
- let numbers: Vec<i32> = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];: This line creates a vector named 'numbers' of type Vec<i32> containing both even and odd numbers.
- let odd_numbers: Vec<i32> = numbers.into_iter().filter(|&x| x % 2 != 0).collect();: This line filters out the even numbers from the 'numbers' vector using the "filter()" method. It creates a new vector named 'odd_numbers' containing only the odd numbers.
- let sub_vector = &odd_numbers[0..5];: This line slices the 'odd_numbers' vector to get a sub-vector containing the first 5 odd numbers.
- println!("Sub-Vector of First 5 Odd Numbers: {:?}", sub_vector);: This line prints the resulting sub-vector to the console using debug formatting. The {:?} format specifier prints the elements of the vector.
Rust Code Editor:
Previous: Rust Vector sorting & slicing.
Next: Rust Vector Mapping & Slicing.
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-arrays-slices-exercise-4.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics