本文介绍了将选项或结果向量转换为仅成功值时,如何避免展开?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Vec 并且我想忽略所有 Err 值,将其转换为 Vec.我可以这样做:

I have a Vec<Result<T, E>> and I want to ignore all Err values, converting it into a Vec<T>. I can do this:

vec.into_iter().filter(|e| e.is_ok()).map(|e| e.unwrap()).collect()

这是安全的,但我想避免使用unwrap.有没有更好的写法?

This is safe, but I want to avoid using unwrap. Is there a better way to write this?

推荐答案

由于 Result 实现IntoIterator,你可以把你的 Vec 转换成一个迭代器(这将是一个迭代器的迭代器),然后把它展平:

Since Result implements IntoIterator, you can convert your Vec into an iterator (which will be an iterator of iterators) and then flatten it:

vec.into_iter().flatten().collect()

  • Iterator::flat_map:

    vec.into_iter().flat_map(|e| e).collect()
    

  • 这些方法也适用于 Option,其中 也实现了 IntoIterator.

    These methods also work for Option, which also implements IntoIterator.

    您还可以将 Result 转换为 Option 并使用 Iterator::filter_map:

    You could also convert the Result into an Option and use Iterator::filter_map:

    vec.into_iter().filter_map(|e| e.ok()).collect()
    

    这篇关于将选项或结果向量转换为仅成功值时,如何避免展开?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

    10-28 15:58