rust - 同时匹配 Result::Err 或 Result::Ok 中的可选字段

标签 rust mapping match

我有一个作为 API 端点的结构,所以我无法更改它的结构

struct Response {
    error: Option<String>,
    results: Vec<String>,
}

如果errorSome,这意味着服务器端失败。

我有一个返回结构的函数:

fn get_results() -> Result<Response, String> {
    unimplemented!()
}

是否可以匹配get_resultsResult错误,和可选的Response.error在同一个match > 分支机构?

这是我的尝试:

fn example() {
    let ret = get_results();
    match ret.map(|resp| resp.error.map_or_else(|| Ok(resp.results), |e| Err(e))) {
        Err(e) => {
            println!("Error: {}", &e);
        }
        Ok(results) => {
            //Handle results
        }
    }
}

但失败了:

error[E0382]: use of moved value: `resp`
  --> src/lib.rs:12:49
   |
12 |     match ret.map(|resp| resp.error.map_or_else(|| Ok(resp.results), |e| Err(e))) {
   |                          ----------             ^^    ---- use occurs due to use in closure
   |                          |                      |
   |                          |                      value used here after move
   |                          value moved here
   |
   = note: move occurs because `resp.error` has type `std::option::Option<std::string::String>`, which does not implement the `Copy` trait

最佳答案

您可以像这样将响应转换为结果:

match resp.error {
    Some(e) => Err(e),
    None => Ok(resp.results),
}

您可以使用 and_then 展平嵌套结果。放在一起,它给出了这个:

ret.and_then(|resp| match resp.error {
    Some(e) => Err(e),
    None => Ok(resp.results),
})

关于rust - 同时匹配 Result::Err 或 Result::Ok 中的可选字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54914952/

相关文章:

rust - 无法从 `use` 附带的外部 crate 中找到符号

java - JPA 将 java.io.File 或 java.nio.file.Path 对象映射到 STRING 列

go - go中修改 map 的约定

mysql - bool 模式匹配 MySQL 奇怪的行为

erlang - 如何在 Erlang 中匹配多个原子?

excel - 在数组中搜索关键字,如果匹配,则从右列返回值

rust - 如何将泛型 T 转换为 String?

sql-server - 如何将所有行作为 tiberius future 的向量?

rust - 找不到指定的过程。 (操作系统错误 127) - #![plu​​gin(rocket_codegen)]

elasticsearch - 动态模板支持默认类型吗?