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

1

7

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`
Kisor answered 30/6, 2020 at 10:41 Comment(1)
If you don't know how to use async (because you can't use it the way you are trying to use it) or even Result, one of the most fundamental Rust type, you've probably missed a few steps in your tutorials. In particular, the book covers Result and the different ways to get data out of it pretty well.Greenock
E
11
  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.

Excrescent answered 30/6, 2020 at 10:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.