相关疑难解决方法(0)

如何在Rust中定义自定义`Error`类型?

我正在编写一个可以返回几个不同错误中的几个错误的函数.

fn foo(...) -> Result<..., MyError> {}
Run Code Online (Sandbox Code Playgroud)

我可能需要定义自己的错误类型来表示这样的错误.我假设这可能是一个enum错误,一些enum变种附带了诊断数据:

enum MyError {
    GizmoError,
    WidgetNotFoundError(widget_name: String)
}
Run Code Online (Sandbox Code Playgroud)

这是最惯用的方式吗?我该如何实现这个Error特性?

error-handling rust

33
推荐指数
3
解决办法
8795
查看次数

期权类型和早期收益。is_none()时返回错误

使用match(如中的bar)似乎是一种常见方法。

#[derive(Debug)]
pub enum MyErrors {
    SomeError,
}

fn foo(x: Option<u64>) -> Result<u64, MyErrors> {
    if x.is_none() {
      return Err(MyErrors::SomeError);
    } 

    // .. some long code where more options
    // are checked and matched 
    // The ok here is just so the code is simple and compiles
    Ok(x.unwrap() * 2)
}

fn bar(x: Option<u64>) -> Result<u64, MyErrors> {
    match x {
        None => {
            return Err(MyErrors::SomeError)?;
        }
        Some(v) => {
           // .. some long code where more options …
Run Code Online (Sandbox Code Playgroud)

rust

1
推荐指数
2
解决办法
160
查看次数

标签 统计

rust ×2

error-handling ×1