In a larger application I have many functions that return a Result<_, _>
. Thanks to ?
I can easily compose those. Unfortunately, my code sometimes naturally results in a Option<Result<_, _>>
. Take this dummy example:
std::env::args().nth(1)
.and_then(|filename| File::open(filename))
To easily compose functions that may fail, I want the Result
at the very "outer level". Of course, match
helps:
match std::env::args().nth(1) {
Some(filename) => File::open(filename).map(|f| Some(f)),
None => Ok(None),
}
But this is rather verbose and annoying to write. I am searching for a function that helps this conversion. I am somehow reminded of the FromIterator<Result<A, E>>
impl for Result<V, E> where V: FromIterator<A>
-- it also pulls the Result
to the outer layer.
So what is the best way to achieve what I want? Writing an own helper function or macro is OK, too.