5 ms·
Rust has an operator for "re-throwing" error: question mark. fn foo() -> Result<int, SomeError> { let result = bar()?; let result2 = baz()?; l
by oleganza 6y ago
Rust has an operator for "re-throwing" error: question mark.
fn foo() -> Result<int, SomeError> {
let result = bar()?;
let result2 = baz()?;
let result3 = bazz()?;
Ok(result + result2 + result3)
}
It's still 100% more explicit about return types and errors, but has the same lightweight feel as in JS/Java/etc.
- flowerlad 6y agoIn your example if bar() returned an error your program still needlessly calls baz() correct? This is why exceptions are better.
- dilap 6y agoNope, the question mark operator is syntax sugar for the "if error, return it" dance. (Cf. https://doc.rust-lang.org/edition-guide/rust-2018/error-handling-and-panics/the-question-mark-operator-for-easier-error-handling.html https://doc.rust-lang.org/edition-guide/rust-2018/error-hand...)
- ben-schaaf 6y agoNope, it returns an error if bar returns an error - immediately. It's essentially shorthand for `if x.is_none() return X;`
- estebank 6y agoThat code desugars to the following fn foo() -> Result<int, SomeError> { let result = match bar() { Ok(val) => val, Err(err) => return Err(err.into()), }; let result2 = match baz() { Ok(val) => val, Err(err) => return Err(err.into()), }; let result3 = match bazz() { Ok(val) => val, Err(err) => return Err(err.into()), }; Ok(result + result2 + result3) }