Rust Function: Check Option Some or None
Write a Rust function that takes an Option
Sample Solution:
Rust Code:
// Function that checks if the input is Some(i32) or None and returns a corresponding string.
fn check_option(option: Option<i32>) -> &'static str {
match option {
Some(_) => "Some",
None => "None",
}
}
fn main() {
// Example usage
let some_value = Some(100);
let none_value: Option<i32> = None;
println!("For Some(100): {}", check_option(some_value)); // Output: Some
println!("For None: {}", check_option(none_value)); // Output: None
}
Output:
For Some(100): Some For None: None
Explanation:
In the exercise above,
- The "check_option()" function takes an Option<i32> as input and returns a string indicating whether the input is 'Some(i32)' or 'None'.
- Inside the function, a 'match' expression is used to pattern match the input 'Option'. If the input is 'Some(_)', meaning it contains a value, it returns "Some". If the input is None, it returns "None".
- In the "main()" function, two examples are demonstrated: one with a 'Some' value (Some(100)) and one with a 'None' value. The "check_option()" function is called with each example, and the result is printed to the console.
Rust Code Editor:
Previous: Rust Function: Check Result Success or Error.
Next: Rust Function: Check vector empty or not.
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