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

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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)