< 返回版块

Lexo-0 发表于 2022-02-08 00:55

Tags:生命周期,异步,borrow checker,lifetime

我尝试为实现了AsyncRead的类型实现Stream<Item=&[u8]>

我先是做了一个包装器


struct Pack<'a,R:Unpin+AsyncBufRead>{
    reader:R,
    _marker:PhantomData<&'a R>
}


然后试着为它实现Stream


impl <'a,R:Unpin+AsyncBufRead>Stream for Pack<'a,R>{
    type Item=&'a [u8];

    fn poll_next(self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> std::task::Poll<Option<Self::Item>> {
        Pin::new(&mut self.reader).poll_fill_buf(cx).map(|v| v.ok())
    }
}


然后我遇到了一些生命周期错误

error[E0495]: cannot infer an appropriate lifetime for lifetime parameter in function call due to conflicting requirements
  --> src/main.rs:15:23
   |
15 |         Pin::new(&mut self.reader).poll_fill_buf(cx).map(|v| v.ok())
   |                       ^^^^
   |
note: first, the lifetime cannot outlive the anonymous lifetime defined here...
  --> src/main.rs:14:28
   |
14 |     fn poll_next(self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> std::task::Poll<Option<Self::Item>> {
   |                            ^^^^^^^^^
note: ...so that the reference type `&mut Pin<&mut Pack<'a, R>>` does not outlive the data it points at
  --> src/main.rs:15:23
   |
15 |         Pin::new(&mut self.reader).poll_fill_buf(cx).map(|v| v.ok())
   |                       ^^^^
note: but, the lifetime must be valid for the lifetime `'a` as defined here...
  --> src/main.rs:11:7
   |
11 | impl <'a,R:Unpin+AsyncBufRead>Stream for Pack<'a,R>{
   |       ^^
note: ...so that the types are compatible
  --> src/main.rs:14:112
   |
14 |       fn poll_next(self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> std::task::Poll<Option<Self::Item>> {
   |  ________________________________________________________________________________________________________________^
15 | |         Pin::new(&mut self.reader).poll_fill_buf(cx).map(|v| v.ok())
16 | |     }
   | |_____^
   = note: expected `<Pack<'a, R> as futures_core::Stream>`
              found `<Pack<'_, R> as futures_core::Stream>`

For more information about this error, try `rustc --explain E0495`.

请问到底发生了什么?我应该如何修复这个错误?

完整链接在此:

https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=f0271eb0360a786e358a2cc6bf586a35


Ext Link: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=f0271eb0360a786e358a2cc6bf586a35

评论区

写评论
Zhanghailin1995 2022-02-11 18:17

不知道这种生命周期问题该如何处理,但是我想到了一种迂回的方法,就是把Stream的 关联类型改成Box<[u8]>,这样通过拷贝一份从来避免了生命周期问题,我不知道还有没有其他的解决方法

use std::pin::Pin;

use futures_core::Stream;
use futures_io::AsyncBufRead;

struct Pack<R: Unpin + AsyncBufRead> {
    reader: R,
}

impl<R: Unpin + AsyncBufRead> Stream for Pack<R> {
    type Item = Box<[u8]>;

    fn poll_next(
        self: Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Option<Self::Item>> {
        Pin::new(&mut self.get_mut().reader)
        .poll_fill_buf(cx)
        .map(|v| v.map(|buf|buf.into()).ok())
    }
}

fn main() {


}
1 共 1 条评论, 1 页