Given this example:
fn function() -> Result<(), &'static str> {
Ok(())
}
fn main() {
function()?; // Compile error
}
I get the error: cannot use the ? operator in a function that returns ()
.
Why can't I use the ?
operator for such functions? Is there syntactic sugar to avoid using a match
statement?
What do you want to happen if function()
returns an Err
result? You can’t use try!
/?
because it causes the containing function to return the same Err
, but main()
can’t return an Err
(it returns ()
, not Result<…>
). If you want to panic, you can use unwrap
:
function().unwrap();
If you want to ignore errors, discard the result:
let _ = function();
Your main
function does not return a Result
. You need to do something with the error case. Probably something like function().expect("oh no! function() failed!!");
, which will cause a panic and error exit in the unlikely event function()
fails. expect()
turns a Result<A,B>
into an A
on success, and panics displaying a combination of your error message and the B
on failure.
Or you could use Result::unwrap()
which works similarly without adding an error message of your own, just using the error value of the Result
.
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