rust example for ? operator

 This is an example of using Result and operator ? in Rust. 

Let's say I have the following division function 

fn div(self, x: f64, y: f64) -> MathResult {
        if y == 0.0 {
            Err(MathError::DivisionByZero)
        } else {
            Ok(x / y)
        }
    }

When i call using the code here, it says "the `?` operator can only be used in a method that returns `Result` or `Option"


fn op1(self, x: f64, y: f64) {
        // if `div` "fails", then `DivisionByZero` will be `return`ed
        let ratio = self.div(x, y)?;
        Ok(10.0)
    }

Rightly pointed out so, if i change my function to this (that returns MathResult), then i was able to use the ? operator.


fn op2(self, x: f64, y: f64) -> MathResult {
        // if `div` "fails", then `DivisionByZero` will be `return`ed
        let ratio = self.div(x, y)?;
        Ok(10.0)
    }

Given that we expect that an error could occur and therefore handle it, we need to have this "handler" somewhere up the call stacks. 


Comments

Popular posts from this blog

The specified initialization vector (IV) does not match the block size for this algorithm