我试图在Rust中实现一个流,以便在补药GRPC处理程序中使用,并遇到了这个困难:创建流的大多数方法都没有容易表达的类型,但是我需要实现的GRPC特性需要一个特定的stream类型。类似的(简化):
// trait to implement
trait GrpcHandler {
type RespStream: futures::Stream<ResponseType> + Send + 'static
fn get_resp_stream() -> Self::RespStream;
}
// a start at implementing it
impl GrpcHandler for MyHandler {
type RespStream = ???; // what do I put here?
fn get_resp_stream() -> Self::RespStream {
futures::stream::unfold((), |_| async {
tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
Some((ResponseType {}, ()))
})
}
}我知道我的流的类型在技术上类似于Unfold<(), ComplicatedFnSignatureWithImpl, ComplicatedFutureSignatureWithImpl>,但是即使我输入了全部内容,编译器也不会高兴它是一个不透明的类型。如何引用此流的类型?
发布于 2022-03-28 22:40:49
不幸的是,在没有动态调度的情况下,稳定锈蚀没有很好的方法来实现。您必须使用dyn Stream,而futures为此提供了BoxStream:
impl GrpcHandler for MyHandler {
type RespStream = futures::stream::BoxStream<'static, ResponseType>;
fn get_resp_stream() -> Self::RespStream {
futures::stream::unfold((), |_| async {
tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
Some((ResponseType {}, ()))
})
.boxed()
}
}如果夜间使用,可以使用不稳定的特性特性来避免动态分派的开销:
#![feature(type_alias_impl_trait)]
impl GrpcHandler for MyHandler {
type RespStream = impl futures::Stream<Item = ResponseType> + Send + 'static;
fn get_resp_stream() -> Self::RespStream {
futures::stream::unfold((), |_| async {
tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
Some((ResponseType {}, ()))
})
}
}https://stackoverflow.com/questions/71654388
复制相似问题