w3resource

Rust Function: Check Option Some or None

Rust Pattern Maching: Exercise-4 with Solution

Write a Rust function that takes an Option and returns "Some" if it's Some(i32) and "None" otherwise.

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.



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/functional-programming/rust-pattern-matching-exercise-4.php