Providing a control resource to complete the closure
I'm going to get my head around Rust trying to implement a singly linked list. Here are my data structures:
struct Linked<T> {
head: Option<Box<Node<T>>>
}
struct Node<T> {
data: T,
next: Option<Box<Node<T>>>
}
Now I would like to add an iterator to this:
struct LinkedIter<'a, T: 'a> {
node: Option<&'a Node<T>>,
}
I wrote a method .iter()
for Linked<T>
that compiles and works fine.
impl<T> Linked<T> {
fn iter(&self) -> LinkedIter<T> {
LinkedIter { node: match self.head {
Some(ref node) => Some(&**node),
None => None
}
}
}
}
This block will now match
convert Option<Box<Linked<T>>>
to Option<&Linked<T>>
. This is just the method Option::map()
. So I reimplemented this method using head.as_ref()
instead head
to avoid ownership of the content Option
in the closure.
impl<T> Linked<T> {
fn iter(&self) -> LinkedIter<T> {
LinkedIter { node:
self.head.as_ref().map(|b: &Box<Node<T>>| &**b)
}
}
}
Unfortunately, a reference created in a closure cannot survive the closure, as it refers to something passed to the closure as a parameter. The compiler complains (slightly paraphrased):
error: cannot deduce the appropriate lifetime for borrowing due to conflicting requirements:
firstly, the lifetime cannot survive the anonymous lifetime # 1 defined by [in close]
but the lifetime must be valid for [function lifetime
iter
]so that the expression [
node:
] is assigned
How can I explain to the compiler that the link will be valid after the closure is closed?
source to share