expected struct `Vec`, found enum `Result` in tokio, cacache and match

1.5k Views Asked by At

I find it difficult to understand what's wrong with the below code. I'm getting expected struct Vec, found enum Result error at Ok(from_cache), but I have adopted the code from https://github.com/platy/update-tracker/blob/843092708906063704442f352231bfbac5b06196/server/src/web/mod.rs#L216-L226

During web scraping, I'm trying to cache the content of the URL in the cache and trying to reuse it.

use std::error::Error;

#[tokio::main]
async fn main() ->  Result<(), Box<dyn Error>> {
    let url: &str = "https://example.com/";
    let html = match cacache::read("./cache", url).await? {
        Ok(from_cache) => String::from_utf8(from_cache),
        Err(_) => {
            let t_html = reqwest::get(url).await?.text().await?;
            cacache::write("./cache", url, &t_html).await?;
            t_html
        },
    };
    println!("html = {:?}", html);

    Ok(())
}

Here's the playground (but, it shows other errors due to missing dependencies). Can anyone please explain this or share any relevant guide to gather more information about this topic?

1

There are 1 best solutions below

4
On BEST ANSWER

Recall that the ? operator unwraps a Result (or Option) by propagating the Err (or None) case out of the current function. Therefore, this expression:

cacache::read("./cache", url).await?

Has type Vec<u8> as the ? operator has unwrapped the Result. If you want to handle errors yourself, then omit the ? operator:

cacache::read("./cache", url).await