无法调用返回结果的函数:找到不透明类型 impl std::future::Future

Dud*_*de4 3 rust reqwest rust-result

我无法从 a 返回函数的结果Result。每个教程只展示如何使用 Result,而不展示如何从中返回值。

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)
}
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

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)
}
Run Code Online (Sandbox Code Playgroud)

Mas*_*inn 6

  1. 你的函数不返回 a Result,它返回 a Future<Result>(因为它是一个异步函数),你需要将它提供给一个执行程序(例如block_on才能运行它;或者,reqwest::blocking如果您不关心异步位,则使用它会更容易
  2. 执行后,您的函数将返回 aResult但您试图将其放入 a 中Vec,但这是行不通的

无关,但是:

println!("{}", a.len().to_string());
Run Code Online (Sandbox Code Playgroud)

{}本质上在to_string内部做了一个,to_string调用是没有用的。