Hello! I have a function that returns a Result<T, E>, and inside that function i have quite a bunch of Iterator::next calls which return an Option. I know how to construct a E from a None. Is there a way to do the following:
fn function(iter: &mut Peekable<impl Iterator<Item = Input>>) -> Result<Output, Error> {
// the function code needs this item, so getting a None is an error
let next_item: Input = iter.next()?;
Ok(next_item as Output)
}
instead of the more lengthy .ok_or(...)?? This would help remove a lot of boilerplate in my code and will improve readability. Example on playground (not my actual code, which is a little more complicated): Rust Playground
I'm on nightly, so if the solution requires unstable features i don't mind at all. Thanks in advance!
Oops, sorry . Anyway, I've heard that there are ongoing efforts to make the Try operator more interoperable, so I guess that the lang team is pursuing other ways to make the conversions that don't involve special language constructs.
Note that it was an intentional design decision to not allow ? on an Option to work in a Result-returning function. That was considered an advantage of the 3058-try-trait-v2 - The Rust RFC Book proposal.
If you make your own type you can choose to allow it to interoperate in certain ways with certain other types, but mixing Option and Result is intentionally not supported.
Using .ok()? or .ok_or(MeaningfulError)? is the intended flow.