Fluffyeater
Fluffyeater

Reputation: 35

Rust: Error, mismatched types. Found std::result::Result

I am making a system to divide two numbers, and if the second number doesn't exist, it just selects the first number. Here is the code:

 let new_num: f32 = match num1/num2 {
     Ok(num) => num,
     Err(error) => num1,
 };

However, it returns: Error: Mismatched types. Expected f32, found std::result::Result
Why is this happening and how can I fix it?

Upvotes: 0

Views: 264

Answers (1)

0x64
0x64

Reputation: 71

The expression num1/num2 is an arithmetic division. Given type f32 for both variables num1 and num2, the result of that expression has the type f32 and not Result.

Example:

let num1: f32 = 2.0;
let num2: f32 = 3.0;
let new_num: f32 = num1 / num2;

If you want to develop logic for something that is able to not exist, you can use an Option. An Option is None if the value does not exist.

Example of intended behaviour:

fn main() {
    assert_eq!(2.0, divide_or_get_first(2.0, None));
    assert_eq!(5.0, divide_or_get_first(10.0, Some(2.0)));
}

fn divide_or_get_first(num1: f32, num2: Option<f32>) -> f32 {
    match num2 {
        Some(value) => {
            num1 / value
        }
        None => {
            num1
        }
    }
}

See:

Upvotes: 1

Related Questions