Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot call a function that returns Result: found opaque type impl std::future::Future

I cannot return a result of a function from a Result. Every tutorial only shows how to use a Result, but not how to return a value from it.

fn main(){
    let mut a: Vec<String> = Vec::new();
    a = gottem();
    println!("{}", a.len().to_string());
    //a.push(x.to_string()
}
async fn gottem() -> Result<Vec<String>, reqwest::Error> {
    let mut a: Vec<String> = Vec::new();
    let res = reqwest::get("https://www.rust-lang.org/en-US/")
        .await?
        .text()
        .await?;
    Document::from(res.as_str())
        .find(Name("a"))
        .filter_map(|n| n.attr("href"))
        .for_each(|x| println!("{}", x));
    Ok(a)
}

I get the following error:

error[E0308]: mismatched types
 --> src/main.rs:13:9
   |
13 |     a = gottem();
   |         ^^^^^^^^ expected struct `std::vec::Vec`, found opaque type
...
18 | async fn gottem() -> Result<Vec<String>, reqwest::Error> {
   | ----------------------------------- the `Output` of this `async fn`'s found opaque type
   |
   = note:   expected struct `std::vec::Vec<std::string::String>`
       found opaque type `impl std::future::Future`
like image 851
Dude4 Avatar asked Jun 30 '20 10:06

Dude4


1 Answers

  1. Your function doesn't return a Result, it returns a Future<Result> (because it's an async function), you need to feed it into an executor (e.g. block_on) in order to run it; alternatively, use reqwest::blocking as it's easier if you don't care for the async bits
  2. Once executor-ed, your function is returning a Result but you're trying to put it into a Vec, that can't work

Unrelated, but:

println!("{}", a.len().to_string());

{} essentially does a to_string internally, the to_string call is not useful.

like image 95
Masklinn Avatar answered Sep 20 '22 11:09

Masklinn