我有一个Vec<Result<T, E>>,我想忽略所有的Err值,将其转换为Vec<T>.我可以做这个:
vec.into_iter().filter(|e| e.is_ok()).map(|e| e.unwrap()).collect()
Run Code Online (Sandbox Code Playgroud)
这是安全的,但我想避免使用unwrap.有没有更好的方法来写这个?
She*_*ter 17
我想忽略所有的
Err价值观
从Resultimplements开始IntoIterator,你可以将你Vec转换为迭代器(它将是迭代器的迭代器),然后将它展平:
vec.into_iter().flatten().collect()
Run Code Online (Sandbox Code Playgroud)vec.into_iter().flat_map(|e| e).collect()
Run Code Online (Sandbox Code Playgroud)这些方法也适用Option,也可以实现IntoIterator.
您还可以将其Result转换为Option并使用 Iterator::filter_map:
vec.into_iter().filter_map(|e| e.ok()).collect()
Run Code Online (Sandbox Code Playgroud)