Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cannot use the `?` operator in a function that returns `()` [duplicate]

Tags:

rust

reqwest

I am very new to rust and I want to write a script to scrape a page and pull all the links from it with their titles. I have failed to even make the get request. :(

fn main() {
    println!("Started!");
    let body = reqwest::get("https://news.ycombinator.com")
    .await?
    .text()
    .await?;

    println!("body = {:?}", body);
}

I am clearly not returning anything however I am confused with the syntax can someone explain the ? operator and also help me fix this issue.

like image 372
Liam Seskis Avatar asked Dec 31 '22 14:12

Liam Seskis


1 Answers

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.

like image 109
user31601 Avatar answered Jan 05 '23 18:01

user31601