Hello!
I'm trying Rust. I implement doubly-linked list in order to get some practical skills. So... I have a structure represents a doubly-linked list, it's ok. There are also Item
structure and Iter
structure. Let's take a look at the code.
type OptItem<T> = Option<Box<Item<T>>>;
#[derive(Debug)]
struct Item<T> {
value: T,
prev: *mut Item<T>,
next: OptItem<T>,
}
pub struct Iter<'a, C: 'a> {
link: Option<&'a mut Item<C>>,
}
So I've got an issue with moving an iterator. Let's take a look at the code.
impl<'a, C: 'a> Iter<'a, C> {
pub fn next(&mut self) {
self.link = match self.link {
Some(Item{ value: _, prev: _, next: Some(next_item) }) => Some(&mut **next_item),
_ => None,
};
}
The error I get looks so
error[E0495]: cannot infer an appropriate lifetime for pattern due to conflicting requirements
--> src/list/mod.rs:60:54
|
60 | Some(Item{ value: _, prev: _, next: Some(next_item) }) => Some(&mut **next_item),
| ^^^^^^^^^
|
note: first, the lifetime cannot outlive the anonymous lifetime #1 defined on the method body at 58:5...
--> src/list/mod.rs:58:5
|
58 | / pub fn next(&mut self) {
59 | | self.link = match self.link {
60 | | Some(Item{ value: _, prev: _, next: Some(next_item) }) => Some(&mut **next_item),
61 | | _ => None,
62 | | };
63 | | }
| |_____^
note: ...so that reference does not outlive borrowed content
--> src/list/mod.rs:60:54
|
60 | Some(Item{ value: _, prev: _, next: Some(next_item) }) => Some(&mut **next_item),
| ^^^^^^^^^
note: but, the lifetime must be valid for the lifetime 'a as defined on the impl at 57:1...
--> src/list/mod.rs:57:1
|
57 | impl<'a, C: 'a> Iter<'a, C> {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^
= note: ...so that the expression is assignable:
expected std::option::Option<&'a mut list::Item<C>>
found std::option::Option<&mut list::Item<C>>
As far as I get the Borrow Checker doesn't know that the available by field next
will live long enough supposing that link
field can be changed. Am I right? Please help me to get what the Borrow Checker means.