w3resource

Rust Function: Check Positive numbers

Rust Basic: Exercise-18 with Solution

Write a Rust function that returns a success value for positive numbers and an error value for negative numbers.

Sample Solution:

Rust Code:

// Define a function named 'check_number' that takes an integer 'num' as input and returns a Result
fn check_number(num: i32) -> Result<i32, &'static str> {
    // Check if 'num' is positive
    if num >= 0 {
        // If 'num' is positive, return it as a success value
        Ok(num)
    } else {
        // If 'num' is negative, return an error value
        Err("Negative number encountered")
    }
}

fn main() {
    // Call the 'check_number' function with positive and negative numbers
    match check_number(5) {
        Ok(value) => println!("Success: {}", value), // Prints: Success: 5
        Err(error) => println!("Error: {}", error),   // This line won't be executed
    }

    match check_number(-3) {
        Ok(value) => println!("Success: {}", value), // This line won't be executed
        Err(error) => println!("Error: {}", error),  // Prints: Error: Negative number encountered
    }
}

Output:

Success: 5
--------------------------------------------
Error: Negative number encountered

Explanation:

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

  • fn check_number(num: i32) -> Result<i32, &'static str> { ... }: This function is defined to take an integer 'num' as input and returns a Result<i32, &'static str>. The "Result" type represents either a success value ('Ok') or an error value ('Err'). The success value is an integer (i32), and the error value is a string slice (&'static str).
  • if num >= 0 { ... } else { ... }: This conditional statement checks if the input number 'num' is greater than or equal to zero. If 'num' is positive or zero, it returns a success value ('Ok'). If 'num' is negative, it returns an error value ('Err').
  • Ok(num): If the input number 'num' is positive or zero, it returns 'num' wrapped in the 'Ok' variant of the 'Result' enum.
  • Err("Negative number encountered"): If the input number 'num' is negative, it returns an error message "Negative number encountered" wrapped in the 'Err' variant of the 'Result' enum.
  • match check_number(5) { ... }: This line calls the "check_number()" function with a positive number 5 and matches the result. Since 5 is positive, the 'Ok' arm will be executed, and it prints the success value.
  • match check_number(-3) { ... }: This line calls the "check_number()" function with a negative number -3 and matches the result. Since -3 is negative, the 'Err' arm will be executed, and it prints the error message.

Rust Code Editor:

Previous: Rust Function: Print optional integer.
Next: Rust Division Error Handling: Pattern Matching Success and Failure Cases.

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.