我有返回一个 Option
或一个 Result
的函数:
fn get_my_result() -> Result<(), Box<Error>> {
lots_of_things()?;
Ok(()) // Could this be omitted?
}
fn get_my_option() -> Option<&'static str> {
if some_condition {
return Some("x");
}
if another_condition {
return Some("y");
}
None // Could this be omitted as well?
}
目前,Ok(())
或None
都不允许省略,如上例所示。这是有原因的吗?将来有可能改变吗?
更新
我们可以使用Fehler编写这样的代码:
#[throws(Box<Error>)]
fn get_my_result() {
let value = lots_of_things()?;
// No need to return Ok(())
}
Fehler 还允许 throw 作为选项。
最佳答案
你不能在 Rust 中省略它。 proposal是为了允许 ()
→ Result<(), _>
强制规则,但它被大量否决然后被拒绝。
A comment很好地解释了为什么这是一个坏主意:
I've gotten very wary of implicit coercion because of JavaScript (yes, I know that's an extreme). I have always loved the explicitness of Rust, and that's why I have favored the other RFC more.
Here is an example of something I'm afraid of
let x = { // Do some stuff ... if blah { Ok(()) } else { Err("oh no"); } }; if let Ok(_) = x { println!("this always prints"); }
Oops... In this case, the type system actually would give false confidence. Scary.
Also, more generally I would like the solution to be specific to exiting a function or block.
当我有很多 Ok(())
在我的代码中,我创建了一个小的辅助函数来使代码更漂亮:
fn ok<E>() -> Result<(), E> {
Ok(())
}
关于rust - 我可以从函数中自动返回 Ok(()) 或 None 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53010103/