0

我有 N futures::Stream,每个Item都有一个时间戳。我想将它们合并排序成一个流,所以我想将所有流转换为 peekable:

fn merge_streams(
    mut streams: Vec<Box<dyn futures::Stream<Item = Data>>>,
) -> impl futures::Stream<Item = Data> {
    async_stream::try_stream! {
          let n = streams.len();
          let streams: Vec<_> = streams.into_iter().map(|s| s.peekable()).collect();
    }
}

我被这个错误困住了:

error: the `peekable` method cannot be invoked on a trait object
     |
     |         let streams: Vec<_> = streams.into_iter().map(|s| s.peekable()).collect();

peekable()需要Self: Sized.

这是否意味着T.peekable()并且Box<T>.peekable需要sizeof(T)在编译时知道?如果是这样,为什么?什么是解决方法?

我试过了

  • Vec<Box<dyn Stream>>
  • Vec<Box<dyn Stream + Sized>>
  • Vec<Box<_>>
  • Vec<&mut dyn Stream>
  • Vec<&mut dyn Stream + Sized>
4

1 回答 1

1

使用BoxStream(由 轻松创建StreamExt::boxed):

use futures::{StreamExt, stream::BoxStream}; // 0.3.5

fn merge_streams(streams: Vec<BoxStream<()>>) {
    streams.into_iter().map(|s| s.peekable()).count();
}
于 2020-08-19T20:38:56.557 回答