Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

rust

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?

like image 676
everett1992 Avatar asked Oct 18 '25 06:10

everett1992


1 Answers

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.

like image 141
user4815162342 Avatar answered Oct 20 '25 22:10

user4815162342