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

后端 未结 1 1666
攒了一身酷
攒了一身酷 2020-12-07 01:20

I have a Vec> and I want to ignore all Err values, converting it into a Vec. I can do this:

相关标签:
1条回答
  • 2020-12-07 01:57

    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()
    
    0 讨论(0)
提交回复
热议问题