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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With