Rust Program: Iterate over Option i32 values
Write a Rust program that iterates over a vector of Option
Sample Solution:
Rust Code:
fn main() {
let options = vec![Some(100), None, Some(200), None, Some(300)]; // Vector of Option values
println!("Original options: {:?}", options); // Print the original vector
// Iterate over the vector and print the value of each Some variant
for option in options {
if let Some(value) = option {
println!("Value of Some variant: {}", value);
}
}
}
Output:
Original options: [Some(100), None, Some(200), None, Some(300)] Value of Some variant: 100 Value of Some variant: 200 Value of Some variant: 300
Explanation:
In the exercise above,
- Define a vector 'options' containing 'Some' and 'None' variants of Option<i32> values.
- The original vector is printed using "println!()".
- We iterate over each element of the vector using a "for" loop.
- Inside the loop, we use pattern matching (if let) to check if the current element is 'Some' variant.
- If it is 'Some', we extract the value and print it using "println!()".
Rust Code Editor:
Previous: Rust Program: Calculate average of Float values.
Next: Rust Program: Sum of Array elements.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics