迭代中游标的生命周期

Lifetime for Cursor in Iteration

use std::io::Cursor;
use bytes::BytesMut;

struct Parser<'a> {
    stream: &'a mut Cursor<&'a [u8]>
}

fn parse<'a>(buf:&'a mut Cursor<&'a [u8]>) -> Option<(usize, &'a str)> {
    None
}

impl<'a> Iterator for Parser<'a> {
type Item = (usize, &'a str);
    fn next(&mut self) -> Option<Self::Item> {
        parse(self.stream)
    }

}

fn main() {
    let mut buf = BytesMut::with_capacity(1024);
    let mut cursor = Cursor::new(&buf[..]);
    let mut parser = Parser {stream: &mut cursor};
}

Playground link

基本上,我想解析一个没有复制但编译失败的buf。有人能帮忙吗?非常感谢!

错误信息:

error[E0495]: cannot infer an appropriate lifetime for lifetime parameter 'a in function call due to conflicting requirements
  --> src/main.rs:15:9
   |
15 |         parse(self.stream)
   |         ^^^^^^^^^^^^^^^^^^
   |
note: first, the lifetime cannot outlive the anonymous lifetime #1 defined on the method body at 14:5...
  --> src/main.rs:14:5
   |
14 |     fn next(&mut self) -> Option<Self::Item> {
   |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
note: ...so that reference does not outlive borrowed content
  --> src/main.rs:15:15
   |
15 |         parse(self.stream)
   |               ^^^^^^^^^^^
note: but, the lifetime must be valid for the lifetime `'a` as defined on the impl at 12:6...
  --> src/main.rs:12:6
   |
12 | impl<'a> Iterator for Parser<'a> {
   |      ^^
note: ...so that the expression is assignable
  --> src/main.rs:15:15
   |
15 |         parse(self.stream)
   |               ^^^^^^^^^^^
   = note: expected `&mut std::io::Cursor<&[u8]>`
              found `&mut std::io::Cursor<&'a [u8]>`

游标内的内容需要不同的生命周期:

struct Parser<'a, 'b> {
    stream: &'a mut Cursor<&'b [u8]>,
}

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=0c36650015dc7fb4d425794fca934242

原因是您的流是可变引用这一事实。如果你让它不可变,一切正常。

我无法解释为什么比 Ryan Levick did in his video he made on lifetimes 更好。

该视频应该是推荐的学习资料之一