1

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?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Kyriet
  • 401
  • 5
  • 8
  • 3
    From the duplicate: *It returns the error if not [OK], calling `Into::into` on the error value to potentially convert it to another type.* The edition guide (and the duplicate, before I edited it) omits that the error value can change type via `?`. That's how your `&str` becomes a `String`. – Shepmaster Jul 07 '21 at 20:46

0 Answers0