返回Stream特征对象的未来

时间:2018-06-12 19:44:06

标签: stream rust future traits

我正在使用futures = "0.1.21" crate而我正在尝试编写一个返回特征对象的函数,该对象是Future的{​​{1}} } Stream s"。在实际程序中,我建立了与服务器的连接,该服务器定期流式传输其操作状态。

期货

我已经能够返回bool"的Future。像这样的特质对象:

bool

现在,我想返回extern crate futures; use futures::{future, Future}; fn future() -> Box<Future<Item = bool, Error = std::io::Error>> { Box::new(future::ok(true)) } fn main() { future(); } Future s&#34;的Stream,但如果我尝试:

bool

无法编译:

extern crate futures;
use futures::{future, stream, Future, Stream};

fn stream_future() -> Box<Future<Item = Stream<Item = bool, Error = std::io::Error>, Error = std::io::Error>> {
    Box::new(future::ok(stream::empty::<bool, std::io::Error>()))
}

fn main() { stream_future(); }

迭代

如果我尝试返回嵌套的error[E0271]: type mismatch resolving `<futures::FutureResult<futures::stream::Empty<bool, std::io::Error>, std::io::Error> as futures::Future>::Item == futures::Stream<Item=bool, Error=std::io::Error>` --> src/main.rs:5:5 | 5 | Box::new(future::ok(stream::empty::<bool, std::io::Error>())) | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected struct `futures::stream::Empty`, found trait futures::Stream | = note: expected type `futures::stream::Empty<bool, std::io::Error>` found type `futures::Stream<Item=bool, Error=std::io::Error>` = note: required for the cast to the object type `futures::Future<Item=futures::Stream<Item=bool, Error=std::io::Error>, Error=std::io::Error>` ,我会遇到类似的问题,例如:

Iterator

失败:

fn iter2() -> Box<Iterator<Item = Iterator<Item = bool>>> {
    Box::new(vec![vec![true].into_iter()].into_iter())
}

其他选项?

我怀疑它是否可能无法嵌套#34;像这样的特征,或者我还没能找到语法。

如果不可能,我是否应该研究另外的设计/模式来完成这样的事情?

1 个答案:

答案 0 :(得分:2)

你的问题让我很困惑。您似乎明白需要 1 来填充未来,那么为什么不将完全相同的逻辑应用于流?

type BoxedStream = Box<Stream<Item = bool, Error = io::Error>>;

fn stream_future() -> Box<Future<Item = BoxedStream, Error = io::Error>> {
    let s: BoxedStream = Box::new(stream::empty());
    Box::new(future::ok(s))
}

另见:

1 在现代Rust中实际上并不总是需要这个。在某些位置,您可以使用impl Trait返回实现特征的值而不用装箱:

fn stream_future() -> impl Future<Item = impl Stream<Item = bool, Error = io::Error>, Error = io::Error> {
    future::ok(stream::empty())
}