[英]Why use empty Result in return?
I often see functions or methods returning Result<(), Error> like this:我经常看到像这样返回 Result<(), Error> 的函数或方法:
fn f() -> Result<(), Error> {
Ok(())
}
In other words such return returns nothing or an error.换句话说,这种返回不返回任何内容或错误。 Why use Result in such situations but not an Option?
为什么在这种情况下使用 Result 而不是 Option ? I think Option would be more suitable, as it effectively returns None or value, in our example - None or an error.
我认为 Option 会更合适,因为它有效地返回 None 或值,在我们的示例中 - None 或错误。
fn f() -> Option<Error> {
None
}
Result
represents success or failure; Result
代表成功或失败; Option
represents any optional value. Option
代表任何可选值。 When you're trying to represent success or failure, even when you could use Option
, Result
is more appropriate.当您试图表示成功或失败时,即使您可以使用
Option
, Result
也更合适。
Because Result
is the type for a failure alternative, it's also more easily used in checks for failure, like with the ?
因为
Result
是失败替代的类型,所以它也更容易用于检查失败,就像?
operator:操作员:
fn read_int() -> Result<u32, ReadIntError> {
let mut buf = [0_u8; 10];
read_line(&mut buf)?; // <-- can’t do this if read_line returns
// Option<ReadError>
Ok(parse_int(&buf)?)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.