如何在 Rust 中引用 impl 输出的类型?
我正在尝试实现Rust的流以在Tonic GRPC处理程序中使用,并遇到了以下困难:创建流的大多数方法都不容易表达类型,但是我需要实现的GRPC特征需要特定的流类型。这样的东西(简化):
// 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 {}, ()))
})
}
}
我知道我的流的类型在技术上是类似的东西,例如 from&lt;(),复杂的fnsignaturewithimpl,complematedfuturesturesignaturewithimpl&gt;
>对它是一种不透明的类型感到高兴。
如何参考此流的类型?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不幸的是,在稳定的 Rust 中没有好的方法可以在没有动态调度的情况下做到这一点。您必须使用
dyn Stream
,并且futures
提供BoxStream
:如果您使用 nightly,则可以使用不稳定的 type_alias_impl_trait 功能可以避免动态调度的开销:
Unfortunately there is no good way in stable Rust to do that without dynamic dispatch. You have to use
dyn Stream
, andfutures
providesBoxStream
for that:If you use nightly, you can use the unstable type_alias_impl_trait feature to avoid the overhead of dynamic dispatch: