繁体   English   中英

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

[英]Why do I get an error about mismatched types when using TryFuture instead of the equivalent Future?

我有以下使用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(())
}

根据我在文档中阅读的内容,我应该能够更改代码以使用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(())
}

编译器抱怨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

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

Playground不起作用,因为tokio仍处于 alpha 阶段,但也有一个合适的Cargo.toml

您的语法目前不起作用。 TryFuture的文档显示您必须暂时将Result包装在Poll中(重点是我的):

 fn try_poll( self: PinMut<Self>, cx: &mut Context ) -> Poll<Result<Self::Ok, Self::Error>> [−]

轮询这个TryFuture ,就好像它是一个Future

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

操场

当这个编译器限制解决时,这种方法将不再是必要的,你将能够做你所做的(或类似的事情)

参考

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM