简体   繁体   中英

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 Error: Mismatched types. Expected f32, found std::result::Result
Why is this happening and how can I fix it?

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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM