w3resource

Rust Function: Square root calculation

Rust Result and Option types: Exercise-4 with Solution

Write a Rust function that calculates the square root of a non-negative number and returns Option<f64>, where None is returned for negative inputs.

Sample Solution:

Rust Code:

// Define a function called calculate_square_root that takes a parameter x of type f64 and returns an Option<f64>
fn calculate_square_root(x: f64) -> Option<f64> {
    // Check if the input x is non-negative
    if x >= 0.0 {
        // If x is non-negative, calculate its square root using sqrt() method and wrap the result in Some
        Some(x.sqrt())
    } else {
        // If x is negative, return None
        None
    }
}

// Define the main function
fn main() {
    // Define a variable x and assign it a non-negative value
    let x = 225.0;
    // Match the result of calculate_square_root function with pattern matching
    match calculate_square_root(x) {
        // If calculate_square_root returns Some(result), print the square root
        Some(result) => println!("Square root of {} is {}", x, result),
        // If calculate_square_root returns None, print an error message
        None => println!("Cannot calculate square root of a negative number"),
    }
}

Output:

Square root of 225 is 15

Explanation:

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

  • Function calculate_square_root(x: f64) -> Option<f64>:
    • This function takes a parameter 'x' of type 'f64' (64-bit floating-point number) and returns an Option<f64>.
    • It checks if the input 'x' is non-negative. If it is, it calculates the square root of 'x' using the 'sqrt()' method and returns it wrapped in 'Some'. If 'x' is negative, it returns 'None'.
  • Main Function:
    • In the "main()" function, a variable 'x' is defined and assigned a non-negative value (225.0 in this case).
    • The calculate_square_root function is called with 'x' as an argument.
    • The result of "calculate_square_root()" is matched using pattern matching (match):
      • If the result is 'Some(result)', meaning the square root was successfully calculated, it prints the square root.
      • If the result is 'None', indicating that the input number was negative, it prints an error message indicating that the square root cannot be calculated for negative numbers.

Rust Code Editor:

Previous: Rust Function: Read file contents.
Next: Rust Function: Date string parsing.

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://www.w3resource.com/rust/error_handling/rust-result-and-option-types-exercise-4.php