I have some vectors like this
let example1: Vec<Option<u64>> = vec![None, None, Some(2), Some(35)];
let example2: Vec<Option<u64>> = vec![Some(5), Some(19), Some(4), Some(6)];
and I want a function that would return None
for example1
but would return Some([5, 19, 4, 6])
for example2
.
In other words, I want a function that returns None
if any of the options are None
, but if all the options are Some
it unwraps them all and returns Some
.
Convert it into an iterator and use .collect::<Option<Vec<_>>>()
.
let output = vec.into_iter().collect::<Option<Vec<_>>>();
or using type annotations
let output: Option<Vec<_>> = vec.into_iter().collect();
See collect()
and the FromIterator
trait implentation it uses for Option
s.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With