The ? operator

If we’re calling something that could error, i.e. it returns a Result, then we can use the ? shorthand if we want.

For example:

let mut username_file = File::open("hello.txt")?;

If the file open is successful, then username_file will be set to the file handle.

If the file open errors, then the resulting error is propagated up

Importantly, the ? operator will convert any errors thrown into the error type defined in the generic of the calling function. For example:

fn read_username_from_file() -> Result<String, MyErrorType> {
	let mut username_file = File::open("hello.txt")?;
}

If the file open fails, the ? operator will convert io::Error into a MyErrorType, provided the custom type has a From trait defined for doing the conversion

The ? operator can be used with Options too. In this case, if the result is None, it will be returned early, otherwise the Some value will be the result of the call. In a way in the context of Option, it’s quite similar to the Typescript ?