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

问题描述

我有一个Vec<Result<T, E>>,我想忽略所有Err值,将其转换为Vec<T>.我可以这样做:

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

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

解决方案

因为 Result实现了IntoIterator ,您可以将Vec转换为迭代器(将是迭代器的迭代器),然后将其展平:

这些方法也可用于 Option 也实现了IntoIterator ./p>


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

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

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()

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

解决方案

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

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


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