Syntax
Some cool Rust syntax
? Operator
?
Operator is used at the end of an expression returning aResult
, and is equivalent to a match expression, where theErr(err)
branch expands to an earlyreturn Err(From::from(err))
, and theOk(ok)
branch expands to anok
expression.
enum MathError {
DivisionByZero,
// ...
}
type MathResult = Result<f64, MathError>;
fn div(x: f64, y: f64) -> MathResult {
if y == 0.0 {
Err(MathError::DivisionByZero)
} else {
Ok(x / y)
}
}
fn op(x: f64, y: f64) -> MathResult {
// if `div` fails, then `DivisionByZero` will be `return`ed
let ratio = div(x, y)?; // actually "return"s if this fails
let ln = ln(ratio);
sqrt(ln)
}
fn op_with_match(x: f64, y: f64) -> MathResult {
match op_(x, y) {
Err(why) => panic!("{}", match why {
MathError::XXX => { ... },
MathError::YYY => { ... },
MathError::DivisionByZero
=> "division by zero",
}),
Ok(value) => println!("{}", value),
}
}
This also works for Option
. Check out the StackOverflow link in the references section below.
References
Examples and quotes from: Rust By Example - ?
Last updated
Was this helpful?