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

7

我无法从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)
}

我遇到了以下错误:

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`

2
如果你不知道如何使用async(因为你试图使用它的方式是错误的),甚至是Rust中最基本的类型之一Result,那么你可能在教程中错过了一些步骤。特别是这本书很好地介绍了Result以及从中获取数据的不同方法。 - mcarton
1个回答

11
  1. 你的函数没有返回一个Result,它返回了一个 Future<Result> (因为它是一个异步函数),你需要将它传递给执行器(例如 block_on)以便运行它;或者如果您不关心异步部分,则可以使用reqwest::blocking,因为它更容易。
  2. 一旦被执行器执行,你的函数会返回一个Result, 但你尝试将其放入一个Vec中,这是无法工作的。

无关的话,但:

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

{}本质上在内部执行了to_string操作,因此to_string调用是无用的。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接