具有正确功能签名的不兼容类型

时间:2018-11-05 02:03:20

标签: rust

我有2个函数返回相同的类型impl Future<Item = (), Error = ()>

extern crate tokio;
extern crate futures;

use tokio::timer::Interval;
use std::time::{Duration, Instant};
use tokio::prelude::*;
use futures::future;

fn run2() -> impl Future<Item = (), Error = ()> {
    future::ok(())
}

fn run() -> impl Future<Item = (), Error = ()> {
    Interval::new(Instant::now(), Duration::from_millis(1000))
        .for_each(move |instant| {
            println!("fire; instant={:?}", instant);
            Ok(())
        })
        .map_err(|e| panic!("interval errored; err={:?}", e))
}

fn main_run() -> impl Future<Item = (), Error = ()> {
    if 1 == 1 {
        run()
    } else {
        run2()
    }
}

fn main() {
    tokio::run(main_run());
}

playground

我正在尝试在main_run中有条件地执行函数,但是出现一个奇怪的错误:

error[E0308]: if and else have incompatible types
  --> src/main.rs:23:5
   |
23 | /     if 1 == 1 {
24 | |         run()
25 | |     } else {
26 | |         run2()
27 | |     }
   | |_____^ expected opaque type, found a different opaque type
   |
   = note: expected type `impl futures::Future` (opaque type)
          found type `impl futures::Future` (opaque type)

两个函数都返回相同的类型:impl Future<Item = (), Error = ()>
为什么编译器不满意?

编辑:
由于它是重复的,因此我在对原始问题的回答中找到了解决方案,但是如果将来有人偶然发现此问题,以下是该特定问题的解决方案:

extern crate tokio;
extern crate futures;

use tokio::timer::Interval;
use std::time::{Duration, Instant};
use tokio::prelude::*;
use futures::future;

fn run2() -> Box<Future<Item = (), Error = ()> + Send> {
    Box::new(future::ok(()))
}

fn run() -> Box<Future<Item = (), Error = ()> + Send> {
    Box::new(Interval::new(Instant::now(), Duration::from_millis(1000))
        .for_each(move |instant| {
            println!("fire; instant={:?}", instant);
            Ok(())
        })
        .map_err(|e| panic!("interval errored; err={:?}", e)))
}

fn main_run() -> impl Future<Item = (), Error = ()> {
    if 1 == 1 {
        run()
    } else {
        run2()
    }
}

fn main() {
    tokio::run(main_run());
}

playgound

0 个答案:

没有答案