【问题标题】:Rust reqwest call on match branches [duplicate]Rust reqwest 调用匹配分支 [重复]
【发布时间】:2020-05-26 16:10:33
【问题描述】:

我想调用两个函数,通过 reqwest 在匹配的两个不同分支上执行 HTTP 调用:

async fn list_projects() -> Result<(), reqwest::Error> {
    let body = reqwest::get("https://...")
        .await?
        .text()
        .await?;
    println!("{:?}", body);
    Ok(())
}

async fn list_categories() -> Result<(), reqwest::Error> {
    let body = reqwest::get("http://...")
        .await?
        .text()
        .await?;
    println!("{:?}", body);
    Ok(())
}

match &args.list {
    List::projects => list_projects(),
    List::categories => list_categories()
}

我收到以下错误:

async fn list_categories() -> Result<(), reqwest::Error> {
   |                                 -------------------------- the `Output` of this `async fn`'s found opaque type
...
49 | /     match &args.list {
50 | |         List::projects => list_projects(),
   | |                           --------------- this is found to be of type `impl std::future::Future`
51 | |         List::categories => list_categories()
   | |                             ^^^^^^^^^^^^^^^^^ expected opaque type, found a different opaque type
52 | |     }
   | |_____- `match` arms have incompatible types
   |
   = note:     expected type `impl std::future::Future` (opaque type at <src/main.rs:29:29>)
           found opaque type `impl std::future::Future` (opaque type at <src/main.rs:38:31>)
   = note: distinct uses of `impl Trait` result in different opaque types
   = help: if both `Future`s have the same `Output` type, consider `.await`ing on both of them

我应该使用std::future::Either吗?

【问题讨论】:

    标签: rust


    【解决方案1】:

    每个异步函数都有不同的类型。如果您的真实代码不是更复杂的东西,您应该能够按照消息的建议进行操作:

    考虑.awaiting 对他们两个

    【讨论】:

    • 我无法将 main 设置为异步,因此无法等待函数调用
    • @cta async-std 有一个 async_main 属性宏,您可以使用该宏将您的 main 转换为 async fn