微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

迭代中游标的生命周期

如何解决迭代中游标的生命周期

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 更好。

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。