首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何引用锈蚀中的refer输出类型?

如何引用锈蚀中的refer输出类型?
EN

Stack Overflow用户
提问于 2022-03-28 22:28:33
回答 1查看 92关注 0票数 4

我试图在Rust中实现一个流,以便在补药GRPC处理程序中使用,并遇到了这个困难:创建流的大多数方法都没有容易表达的类型,但是我需要实现的GRPC特性需要一个特定的stream类型。类似的(简化):

代码语言:javascript
复制
// 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>,但是即使我输入了全部内容,编译器也不会高兴它是一个不透明的类型。如何引用此流的类型?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-03-28 22:40:49

不幸的是,在没有动态调度的情况下,稳定锈蚀没有很好的方法来实现。您必须使用dyn Stream,而futures为此提供了BoxStream

代码语言:javascript
复制
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()
    }
}

如果夜间使用,可以使用不稳定的特性特性来避免动态分派的开销:

代码语言:javascript
复制
#![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 {}, ()))
        })
    }
}
票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71654388

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档