The question mark operator can only be used inside functions that return a std::Result
. Roughly speaking, you can think of x?
as meaning
match x {
Err(e) => return Err(e),
Ok(y) => y,
}
(see documentation here)
What do you want to happen when await
produces an error result? If you're not expecting an error to ever occur, then it should be safe to tell Rust to panic (i.e. crash) if it does. This is what Result::unwrap
is for:
fn main() {
println!("Started!");
let body = reqwest::get("https://news.ycombinator.com")
.await
.unwrap()
.text()
.await
.unwrap();
println!("body = {:?}", body);
}
More likely, you should handle error results responsibly with some well defined behaviour. This could be attempting to recover (i.e. trying something different), or maybe logging an error message and exiting with a non-zero code if you're in the top-level main
function. The simple way to do either of these would be to use a match
statement yourself.
From this perspective, it becomes clear what the intent of the ?
operator is: it's a way of saying "It's not my responsibility to handle this error – it's the responsibility of the code that called me." The important thing here is that it still has to be someone's responsibility to decide how to handle errors.