问题描述
我有一个Vec<Result<T, E>>
,我想忽略所有Err
值,将其转换为Vec<T>
.我可以这样做:
vec.into_iter().filter(|e| e.is_ok()).map(|e| e.unwrap()).collect()
这是安全的,但我想避免使用unwrap
.有没有更好的方法来写这个?
因为 Result
实现了IntoIterator
,您可以将Vec
转换为迭代器(将是迭代器的迭代器),然后将其展平:
-
vec.into_iter().flatten().collect()
-
vec.into_iter().flat_map(|e| e).collect()
这些方法也可用于 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:
vec.into_iter().flatten().collect()
vec.into_iter().flat_map(|e| e).collect()
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()
这篇关于将选项或结果向量仅转换为成功值时,如何避免拆封?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!