Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR RUST

armanriazi•rust•t•opt•?

The error message also mentioned that ? can be used with Option<T> values as well. As with using ? on Result, you can only use ? on Option in a function that returns an Option. The behavior of the ? operator when called on an Option<T> is similar to its behavior when called on a Result<T, E>: if the value is None, the None will be returned early from the function at that point. If the value is Some, the value inside the Some is the resulting value of the expression and the function continues
This pattern of propagating errors is so common in Rust that Rust provides the question mark operator ? to make this easier.
Sample : propagating errors
    match f.read_to_string(&mut s) {
        Ok(_) => Ok(s),
        Err(e) => Err(e),
    }

what the ? operator does: error values that have the ? operator called on them go through the from function, defined in the From trait in the standard library, which is used to convert errors from one type into another. When the ? operator calls the from function, the error type received is converted into the error type defined in the return type of the current function. This is useful when a function returns one error type to represent all the ways a function might fail, even if parts might fail for many different reasons. As long as there’s an impl From<OtherError> for ReturnedError to define the conversion in the trait’s from function, the ? operator takes care of calling the from function automatically.

In the context of Listing 9-7, the ? at the end of the File::open call will return the value inside an Ok to the variable f. If an error occurs, the ? operator will return early out of the whole function and give any Err value to the calling code. The same thing applies to the ? at the end of the read_to_string call.

The ? operator eliminates a lot of boilerplate and makes this function’s implementation simpler. We could even shorten this code further by chaining method calls immediately after the ?

{either option&result :
you can’t mix and match. The ? operator won’t automatically convert a Result to an Option or vice versa; in those cases, there are methods like the ok method on Result or the ok_or method on Option that will do the conversion explicitly.
}
 
PREVIOUS NEXT
Tagged:
ADD COMMENT
Topic
Name
7+3 =