The ? operator for easier error handling from the Rust Edition Guide says that this line:
let mut f = File::open("username.txt")?;
is a shorthand for this entire match statement:
let f = File::open("username.txt");
let mut f = match f {
Ok(file) => file,
Err(e) => return Err(e),
};
What is the actual difference between the ?
operator and returning Err(e)
?
Consider the code:
fn main() {
println!("{:?}", foo());
}
fn foo() -> Result<(), String> {
Err("error")?; // (1) this is fine
//return Err("error"); // (2) compilation error: 'mismatched types'
Ok(())
}
If the ?
operator was just a sugar-syntax for returning appropriate Err
from function then I would expect (1) and (2) to treated in the same way by the compiler. What is the difference we can observe in the example above?