首页 > 解决方案 > 返回 Stream trait 对象的 Future

问题描述

我正在使用futures = "0.1.21"板条箱,并且正在尝试编写一个函数,该函数返回一个特征对象,该对象是“ Futureof a Streamof bools”。在实际程序中,我正在建立与服务器的连接,该服务器定期传输其操作状态。

期货

我已经能够像这样返回一个 " Futureof a 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(); }

现在我想返回一个“ Futureof a Streamof bools”,但如果我尝试:

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())
}

失败:

error[E0271]: type mismatch resolving `<std::vec::IntoIter<std::vec::IntoIter<bool>> as std::iter::Iterator>::Item == std::iter::Iterator<Item=bool>`
 --> src/main.rs:2:5
  |
2 |     Box::new(vec![vec![true].into_iter()].into_iter())
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected struct `std::vec::IntoIter`, found trait std::iter::Iterator
  |
  = note: expected type `std::vec::IntoIter<bool>`
             found type `std::iter::Iterator<Item=bool>`
  = note: required for the cast to the object type `std::iter::Iterator<Item=std::iter::Iterator<Item=bool>>`

其他选择?

我怀疑要么不可能“嵌套”这样的特征,要么我无法弄清楚语法。

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

标签: streamrustfuturetraits

解决方案


你的问题让我很困惑。您似乎明白您需要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())
}

推荐阅读