everett1992
everett1992

Reputation: 2661

Can I use the question mark operator (?) in a divergent function that returns the never type (!)?

I'm writing Rust for an embedded project and my main function's signature is

#[entry]
fn main() -> !

I understand that this means that it will never return, and I generally enter an infinite loop at the end of main.

I want to use the ? try operator in my main function, but I couldn't search the docs for rust ? in !. How do I spell this out in words?

Can I use ? in a () -> ! function?

Upvotes: 4

Views: 964

Answers (1)

user4815162342
user4815162342

Reputation: 154916

can I use ? in a () -> ! function

No. The ? operator is an expression where X? is interpreted roughly as:

match X {
    Ok(success_value) => success_value,
    Err(err_value) => {
         return Err(err_value);  // returns from the enclosing function
    }
}

Note how the ? expression implies a return from the function that uses it. For X? to compile, the function's return type needs to be a Result whose error variant is compatible with the error variant of X. A function that returns the never type ! specifically promises never to return, so its return type is not compatible with the return implied by the ? operator.

A function that never returns should either handle error results using match or equivalent to choose the appropriate action, or call .unwrap() or .expect() to convert them into panic.

Upvotes: 7

Related Questions