rust - 我可以从函数中自动返回 Ok(()) 或 None 吗?

标签 rust

我有返回一个 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/

相关文章:

rust - 将数据从函数参数(从线程)发送到 mpsc channel

rust - 如何将可见性 token 传递给位标志!宏?

closures - 在多个闭包之一中捕获相同的变量

json - 如何从另一个文件调用函数并在Web中提取

asynchronous - 如何实现对异步fn进行轮询的Future或Stream?

rust - 如何查找/生成夜间文档?

concurrency - 用共享的数据库连接和缓存编写Rust微服务的惯用方式是什么?

rust - 在 Rust 中计算两个 f64 向量的点积的最快方法是什么?

generics - 解决特征实现冲突

rust - 为什么我的结构生命周期不够长?