[英]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
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.表达式num1/num2
是算术除法。 Given type f32
for both variables num1
and num2
, the result of that expression has the type f32
and not Result
.给定变量num1
和num2
的类型f32
,该表达式的结果具有类型f32
而不是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
.如果你想为不存在的东西开发逻辑,你可以使用Option
。 An Option
is None
if the value does not exist.如果值不存在,则Option
为None
。
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:看:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.