如何在 Rust 中引用 impl 输出的类型?

mwl*_*lon 4 traits rust opaque-types

我试图在 Rust 中实现一个流,以便在 tonic 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 {}, ()))
    })
  }
}
Run Code Online (Sandbox Code Playgroud)

我知道我的流的类型在技术上类似于Unfold<(), ComplicatedFnSignatureWithImpl, ComplicatedFutureSignatureWithImpl>,但即使我输入了整个内容,编译器也不会因为它是不透明类型而感到高兴。我如何引用该流的类型?

Cha*_*man 6

不幸的是,在稳定的 Rust 中没有好的方法可以在没有动态调度的情况下做到这一点。您必须使用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()
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您使用 nightly,则可以使用不稳定的type_alias_impl_trait功能来避免动态调度的开销:

#![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 {}, ()))
        })
    }
}
Run Code Online (Sandbox Code Playgroud)