Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert a Vec<Option<T>> to an Option<Vec<T>>

Tags:

rust

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.

like image 606
timotree Avatar asked Feb 20 '19 01:02

timotree


1 Answers

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 Options.

like image 135
timotree Avatar answered Nov 20 '22 05:11

timotree