问题描述
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};
}
基本上,我想解析一个没有副本但编译失败的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]>,}
原因是因为您的流是可变引用。如果您使它不可变,则一切正常。
我无法解释为什么比 Ryan Levick did in his video he made on lifetimes 更好。
那个视频应该是推荐的学习资料之一?