w3resource

Rust Function: Safe Division

Rust Result and Option types: Exercise-8 with Solution

Write a Rust function that divides two numbers and returns Result<f64, &'static str>, indicating success or division by zero error.

Sample Solution:

Rust Code:

fn divide(x: f64, y: f64) -> Result<f64, &'static str> {
    // Check if the divisor is not zero
    if y != 0.0 {
        // If not zero, perform the division and return the result
        Ok(x / y)
    } else {
        // If divisor is zero, return an error message
        Err("Division by zero")
    }
}

fn main() {
    // Test cases
    let dividend = 10.0; // Dividend
    let divisor = 2.0; // Non-zero divisor
    let zero_divisor = 0.0; // Zero divisor

    // Test the divide function with a non-zero divisor
    match divide(dividend, divisor) {
        Ok(result) => println!("Result of division: {}", result),
        Err(error_msg) => println!("Error: {}", error_msg),
    }

    // Test the divide function with a zero divisor
    match divide(dividend, zero_divisor) {
        Ok(result) => println!("Result of division: {}", result),
        Err(error_msg) => println!("Error: {}", error_msg),
    }
}

Output:

Result of division: 5
Error: Division by zero

Explanation:

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

  • The "divide()" function takes two 'f64' numbers as input parameters and attempts division.
  • Inside the function, it first checks if the divisor ('y') is not zero. If it's not zero, the function performs the division and returns the result wrapped in 'Ok'.
  • If the divisor is zero, the function returns an error message wrapped in 'Err'.
  • The "main()" function provides test cases for both scenarios: division with a non-zero divisor and division by zero.

Rust Code Editor:

Previous: Rust Function: Hex string to integer.
Next: Rust Function: Filter odd numbers.

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.