Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
869 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...