我正在尝试将 AsyncRead
包装在另一个 AsyncRead
中(并对其进行一些数据处理)。但是,在尝试存储 .read()
的 Future
时,我遇到了生命周期问题:self has an anonymous lifetime '_ but it needs to satisfy a 'static lifetime requirement
。
代码:
pub struct AsyncReadWrap {
input: Pin<Box<dyn AsyncRead + 'static>>,
future: Option<Pin<Box<dyn Future<Output = std::io::Result<usize>>>>>
}
impl AsyncReadWrap {
pub fn new(input: impl AsyncRead + Unpin + 'static) -> AsyncReadWrap {
AsyncReadWrap {
input: Box::pin(input),
future: None
}
}
}
impl AsyncRead for AsyncReadWrap {
fn poll_read(self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>) -> Poll<std::io::Result<()>> {
let mut buffer = [0u8; 2048];
let future = self.input.as_mut().read(&mut buffer);
self.future = Some(Box::pin(future));
Poll::Pending
}
}
我对异步操作还很陌生,感到奇怪的是在 poll
函数中没有简单的方法可以使用 await
。谢谢。
poll_read
,但是由于某些原因它不能读取多次。可能是我的代码有bug。如果我的流程解决方法失败了,我会再试一次。 - Makalone LOgmanPoll::Pending
,执行器将不会再次轮询您,除非您告诉它唤醒您。如果您选择采用更低级别的异步实现,我会在答案中提供一些资源链接以帮助您入门。 - Ibraheem Ahmedasync
/await
还非常新,许多较低级别的细节仍然向初学者公开。 - Ibraheem Ahmed