w3resource

Rust Division Error Handling: Pattern Matching Success and Failure Cases

Rust Basic: Exercise-19 with Solution

Write a Rust program that handles the result of a division operation, using pattern matching to distinguish between success and failure.

Sample Solution:

Rust Code:

fn main() {
    // Define dividend and divisor
    let dividend = 10;
    let divisor = 0; // Change to 0 to simulate division by zero error

    // Perform the division operation
    let result = divide(dividend, divisor);

    // Match on the result to handle success and failure cases
    match result {
        // If division is successful, print the result
        Ok(value) => println!("Result of division: {}", value),
        // If division fails (division by zero), print an error message
        Err(error) => println!("Error: {}", error),
    }
}

// Define a function named 'divide' that performs division and returns a Result
fn divide(dividend: i32, divisor: i32) -> Result<i32, &'static str> {
    // Check if divisor is zero
    if divisor == 0 {
        // If divisor is zero, return an error
        Err("Division by zero is not allowed!")
    } else {
        // If divisor is non-zero, perform the division and return the result
        Ok(dividend / divisor)
    }
}

Output:

Error: Division by zero is not allowed!

Explanation:

Here's a brief explanation of the above Rust code:

  • fn main() { ... }: This is the entry point of the program.
  • let dividend = 10; and let divisor = 0;: These lines define the dividend and divisor variables for the division operation. Change the value of 'divisor' to 0 to simulate a division by zero error.
  • let result = divide(dividend, divisor);: This line calls the "divide()" function with 'dividend' and 'divisor' as arguments and stores the result in the 'result' variable.
  • match result { ... }: This is a match expression that matches on the 'result' to handle both success and failure cases.
  • Ok(value) => println!("Result of division: {}", value),: This arm of the match expression is executed if division is successful ('Ok'). It prints the result of the division.
  • Err(error) => println!("Error: {}", error),: This arm of the match expression is executed if division fails (division by zero) ('Err'). It prints an error message indicating division by zero.
  • fn divide(dividend: i32, divisor: i32) -> Result<i32, &'static str> { ... }: This function named divide takes two integers dividend and divisor as input and returns a Result. If the division succeeds, it returns Ok(result), where result is the quotient. If division by zero occurs, it returns Err("Division by zero is not allowed!").

Rust Code Editor:

Previous: Rust Function: Check Positive numbers.

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/basic/rust-basic-exercise-19.php