Rust Division Error Handling: Pattern Matching Success and Failure Cases
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:
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.