Syntax

Some cool Rust syntax

? Operator

? Operator is used at the end of an expression returning a Result, and is equivalent to a match expression, where the Err(err) branch expands to an early return Err(From::from(err)), and the Ok(ok) branch expands to an ok 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

Last updated