Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot use `?` operator for functions that return Result<(), error> [duplicate]

Tags:

rust

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?

like image 450
Lev Avatar asked Dec 28 '17 23:12

Lev


2 Answers

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();
like image 95
Ry- Avatar answered Nov 19 '22 01:11

Ry-


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.

like image 28
NovaDenizen Avatar answered Nov 18 '22 23:11

NovaDenizen