为什么在使用 TryFuture 而不是等效的 Future 时会收到有关类型不匹配的错误?

Vic*_*aev 5 future rust

我有以下使用的工作代码Future

use futures::{future, Future};

fn fut_res() -> impl Future<Output = Result<(), failure::Error>> {
    future::ok::<(), failure::Error>(())
}

#[tokio::main]
async fn main() -> Result<(), failure::Error> {
    if let Err(e) = fut_res().await {
        println!("{:?}", e);
    }

    Ok(())
}
Run Code Online (Sandbox Code Playgroud)

根据我在文档中阅读的内容,我应该能够更改要使用的代码,TryFuture如下所示:

use futures::{future, TryFuture};

fn try_fut() -> impl TryFuture<Ok = (), Error = failure::Error> {
    future::ok::<(), failure::Error>(())
}

#[tokio::main]
async fn main() -> Result<(), failure::Error> {
    if let Err(e) = try_fut().await {
        println!("{:?}", e);
    }

    Ok(())
}
Run Code Online (Sandbox Code Playgroud)

编译器抱怨try_fut必须返回关联的类型Output,但根据定义,该类型 Result<(), failure::Error>

error[E0308]: mismatched types
 --> src/lib.rs:9:12
  |
9 |     if let Err(e) = try_fut().await {
  |            ^^^^^^ expected associated type, found enum `std::result::Result`
  |
  = note: expected type `<impl futures_core::future::TryFuture as core::future::future::Future>::Output`
             found type `std::result::Result<_, _>`
  = note: consider constraining the associated type `<impl futures_core::future::TryFuture as core::future::future::Future>::Output` to `std::result::Result<_, _>` or calling a method that returns `<impl futures_core::future::TryFuture as core::future::future::Future>::Output`
  = note: for more information, visit https://doc.rust-lang.org/book/ch19-03-advanced-traits.html
Run Code Online (Sandbox Code Playgroud)

我如何向编译器解释这一点?

Playground无法工作,因为tokio仍处于 alpha 阶段,但也有一个合适的Cargo.toml.

Ahm*_*sud 2

您的语法目前不起作用。的文档TryFuture表明您必须将其包装ResultPoll暂时

\n\n
\n
fn try_poll(\n    self: PinMut<Self>, \n    cx: &mut Context ) -> Poll<Result<Self::Ok, Self::Error>> [\xe2\x88\x92]\n
Run Code Online (Sandbox Code Playgroud)\n\n

对此进行民意调查TryFuture,就好像它是一个Future.

\n\n

此方法是编译器限制的权宜之计,该限制阻止我们直接继承该Future特征;将来将不再需要它。

\n
\n\n

操场

\n\n

当此编译器限制解决后,将不再需要此方法,您将能够执行您所做的操作(或类似的操作)

\n\n

参考

\n\n\n