Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I avoid unwrap when converting a vector of Options or Results to only the successful values?

Tags:

iterator

rust

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?

like image 740
jgillich Avatar asked Mar 15 '16 19:03

jgillich


1 Answers

I want to ignore all Err values

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

  • Iterator::flatten:

    vec.into_iter().flatten().collect() 
  • Iterator::flat_map:

    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() 
like image 67
Shepmaster Avatar answered Oct 10 '22 13:10

Shepmaster