当 Iterator::map 返回 Result::Err 时,如何停止迭代并返回错误? [英] How do I stop iteration and return an error when Iterator::map returns a Result::Err?

查看:53
本文介绍了当 Iterator::map 返回 Result::Err 时,如何停止迭代并返回错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个返回 Result 的函数:

I have a function that returns a Result:

fn find(id: &Id) -> Result<Item, ItemError> {
    // ...
}

然后另一个像这样使用它:

Then another using it like this:

let parent_items: Vec<Item> = parent_ids.iter()
    .map(|id| find(id).unwrap())
    .collect();

如何处理任何 map 迭代中的失败情况?

How do I handle the case of failure inside any of the map iterations?

我知道我可以使用 flat_map 并且在这种情况下错误结果将被忽略:

I know I could use flat_map and in this case the error results would be ignored:

let parent_items: Vec<Item> = parent_ids.iter()
    .flat_map(|id| find(id).into_iter())
    .collect();

Result 的迭代器根据成功状态有 0 或 1 项,如果为 0,flat_map 将过滤掉.

Result's iterator has either 0 or 1 items depending on the success state, and flat_map will filter it out if it's 0.

但是,我不想忽略错误,我想让整个代码块停止并返回一个新错误(基于地图中出现的错误,或者只需转发现有错误).

However, I don't want to ignore errors, I want to instead make the whole code block just stop and return a new error (based on the error that came up within the map, or just forward the existing error).

如何在 Rust 中最好地处理这个问题?

How do I best handle this in Rust?

推荐答案

Result 实现FromIterator,所以你可以将Result移到外面,迭代器会处理剩下的事情(包括在出现错误时停止迭代找到了).

Result implements FromIterator, so you can move the Result outside and iterators will take care of the rest (including stopping iteration if an error is found).

#[derive(Debug)]
struct Item;
type Id = String;

fn find(id: &Id) -> Result<Item, String> {
    Err(format!("Not found: {:?}", id))
}

fn main() {
    let s = |s: &str| s.to_string();
    let ids = vec![s("1"), s("2"), s("3")];

    let items: Result<Vec<_>, _> = ids.iter().map(find).collect();
    println!("Result: {:?}", items);
}

游乐场

这篇关于当 Iterator::map 返回 Result::Err 时,如何停止迭代并返回错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆