w3resource

Rust Function: Check Result Success or Error

Rust Pattern Maching: Exercise-3 with Solution

Write a Rust function that takes a Result and returns "Success" if it's Ok(i32) and "Error" if it's Err(&str).

Sample Solution:

Rust Code:

// Define a function that takes a Result<i32, &str> and returns a static string slice
fn check_result(result: Result<i32, &str>) -> &'static str {
    // Pattern match on the Result
    match result {
        // If it's Ok(i32), return "Success"
        Ok(_) => "Success",
        // If it's Err(&str), return "Error"
        Err(_) => "Error",
    }
}

fn main() {
    // Example usage:
    let success_result: Result<i32, &str> = Ok(42);
    let error_result: Result<i32, &str> = Err("An error occurred");

    println!("Success result: {}", check_result(success_result)); // Output: Success
    println!("Error result: {}", check_result(error_result)); // Output: Error
}

Output:

Success result: Success
Error result: Error

Explanation:

The above Rust code defines a function "check_result()" that takes a Result<i32, &str> as input and returns a &'static str. Inside the function, there's a pattern matching with 'match' on the 'Result'. If the 'Result' is Ok(_), indicating a successful computation with an integer result, it returns "Success". If the 'Result' is Err(_), indicating an error with an error message as a string slice, it returns "Error".

In the "main()' function, two example 'Result' instances are created: one representing a successful result (Ok(42)) and the other representing an error (Err("An error occurred")). The "check_result()" function is then called with these instances, and the results are printed out.

Rust Code Editor:


Previous: Rust Function: Check vowel or consonant.
Next: Rust Function: Check Option Some or None.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.