rust - 如何处理unwrap_or_else中的异常(Err)?

标签 rust

struct OverflowError {}

fn test_unwrap() -> Result<String, OverflowError> {
    let a: Result<String, u8> = Err(100);

    let a: String = a.unwrap_or_else(|err| {
        if err < 100 {
            String::from("Ok")
        } else {
            // I want to return from the function (not just the closure)
            // This is compile error with error:
            // "the ? operator can only be used in a closure that returns Result or Option"
            Err(OverflowError {})?
        }
    });

    Ok(a)
}

error[E0277]: the `?` operator can only be used in a closure that returns `Result` or `Option` (or another type that implements `std::ops::Try`)
  --> src/lib.rs:13:13
   |
6  |       let a: String = a.unwrap_or_else(|err| {
   |  ______________________________________-
7  | |         if err < 100 {
8  | |             String::from("Ok")
9  | |         } else {
...  |
13 | |             Err(OverflowError {})?
   | |             ^^^^^^^^^^^^^^^^^^^^^^ cannot use the `?` operator in a closure that returns `std::string::String`
14 | |         }
15 | |     });
   | |_____- this function should return `Result` or `Option` to accept `?`
   |
   = help: the trait `std::ops::Try` is not implemented for `std::string::String`
   = note: required by `std::ops::Try::from_error`

这是我的代码的简化版本。基本上在unwrap_or_else闭包内,可能会出现条件错误(例如IOError)。在这种情况下,我想尽早终止该功能(使用?)。但是显然它不起作用,因为它当前处于闭包中,并且闭包不希望使用Result类型。

处理此问题的最佳做法是什么?

最佳答案

您想要的是 or_else() :

struct OverflowError {}

fn test_unwrap() -> Result<String, OverflowError> {
    let a: Result<String, u8> = Err(100);

    let a: String = a.or_else(|err| {
        if err < 100 {
            Ok(String::from("Ok"))
        } else {
            Err(OverflowError {})
        }
    })?;

    Ok(a)
}

简化:

struct OverflowError {}

fn test_unwrap() -> Result<String, OverflowError> {
    Err(100).or_else(|err| {
        if err < 100 {
            Ok(String::from("Ok"))
        } else {
            Err(OverflowError {})
        }
    })
}

关于rust - 如何处理unwrap_or_else中的异常(Err)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61995572/

相关文章:

rust - 为什么不能在同一结构中存储值和对该值的引用?

types - 什么是正确的数据类型,以使函数能够在Rust的迭代器之间复制,并且功能尽可能广泛?

rust - 引用上的Rust调用方法

enums - 为什么这个 Rust 枚举没有变小?

generics - 为什么 Rust 不能将带有生命周期参数的异步函数强制转换为函数指针?

arrays - 线程 '<main>' 在创建大型数组时已溢出其堆栈

rust - 有没有办法在绑定(bind)超出范围之前释放绑定(bind)?

rust - 结构所有权

tcp - 创建一个监听端口的简单 Rust 守护进程

rust - 线程局部 RefCell 作为 Rust 中局部变量的替换