There should really be a more real-world example, the current code (and your alternative version) is just redundant and equivalent to
fn try_option_some() -> Option<u8> {
Some(1)
} fn try_option_some() -> Option<u8> {
Some(1)
} fn f() -> Result<A, E>
fn g() -> Result<B, E>
Then you can write fn h() -> Result<(A,B), E> {
let x = f()?;
let y = g()?;
Ok((x, y))
}
rather than having to do something like fn h() -> Result<(A,B), E> {
match f() {
Ok(x) => {
match g() {
Ok(y) => Ok((x,y)),
Err(e) => Err(e)
}
},
Err(e) => Err(e),
}
}
(written from memory, please excuse syntax errors)What's new is that this also works with Option<A> now.
Another sane alternative here is using and_then, map, etc.
Writing from memory too:
fn h() -> Result<(A, B), E> {
f().and_then(|x| g().map(|y| (x, y)))
}
..which seems to be a different style of control flow to choose from. On one hand, I suppose one may avoid using and_then with code dealing with side effects. On another hand, ? seems restricted to being used inside functions that have to return a a single type (like Result) they operate on.> functions that have to return a single type
Well, all functions have to return a single type, though that type may be a composite type, like a tuple.
Less pedantically, `?` lets you (well, will let you) unwrap values and convert their error cases between each other. So once the next round of stabilization happens, if you have a function that returns Results, you can mix ? on Options and Results in the body, and vice versa. And it can be extended for other types too. Basically, it's an early return "protocol" if you will.
do_this(x).ok_or(CustomError::ThisError)?;