[英]Rust async issues with local variables
I have a method like this:我有这样的方法:
pub async fn build_incoming_stream(&mut self) -> impl Stream<Item = Result<
SslStream<<tokio::net::tcp::Incoming<'_> as TryStream>::Ok>,
Box<dyn Error + Send + Sync + 'static>,>,>
{
let addr = self.address.parse::<SocketAddr>()
.expect("Couldn't parse socket address");
let mut listener = TcpListener::bind(addr)
.await
.expect("Couldn't bind address");
let acceptor = self.configure_acceptor()
.await
.expect("configuring acceptor failed");
incoming(listener.incoming(), acceptor.clone())
}
Where fn incoming is:其中 fn 传入是:
pub fn incoming<S>(incoming: S,acceptor: SslAcceptor,) -> impl Stream<Item =
Result<SslStream<S::Ok>, StreamError>> where
S: TryStream + Unpin,
S::Ok: AsyncRead + AsyncWrite + Send + Sync + Debug + Unpin + 'static,
S::Error: Into<StreamError>,
{
let mut incoming = incoming;
try_stream! {
while let Some(stream) = incoming.try_next().await? {
let tls = tokio_openssl::accept(&acceptor, stream).await?;
let ssl = SslStream {
inner: tls
};
yield ssl;
}
}
}
The compiler keeps complaining that I can't return a value referencing local data, on the last line of build_incomig_stream fn:编译器一直抱怨我无法在 build_incomig_stream fn 的最后一行返回引用本地数据的值:
cannot return value referencing local data
listener
returns a value referencing data owned by the current function无法返回引用本地数据listener
器的值返回引用当前 function 拥有的数据的值
I've tried to wrap it in async move block, to capture listener, but with no luck... any ideas how could I resolve or work around this issue?我试图将它包装在异步移动块中以捕获侦听器,但没有运气......任何想法我该如何解决或解决这个问题?
Seems that tcp listener already implements stream, so this code works:似乎 tcp 监听器已经实现了 stream,所以这段代码有效:
pub async fn build_incoming_stream(
&mut self,
) -> impl Stream<
Item = Result<
SslStream<<tokio::net::tcp::Incoming<'_> as TryStream>::Ok>,
Box<dyn Error + Send + Sync + 'static>,
>,
> {
let addr = self
.address
.parse::<SocketAddr>()
.expect("Couldn't parse socket address");
let acceptor = self
.configure_acceptor()
.await
.expect("configuring acceptor failed");
incoming(
TcpListener::bind(addr)
.await
.expect("Couldn't bind address"),
acceptor.clone(),
)
}
The issue with code posted in question was in相关代码的问题在于
pub fn incoming(&mut self) -> Incoming<'_> {
Incoming::new(self)
}
because incoming takes tcp listener as mutable reference and this was causing trouble.因为传入将 tcp 侦听器作为可变引用,这造成了麻烦。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.