I have a tree structure that uses a HashMap in an RwLock to represent the children of a node, but my method to recurse down the tree to insert a value appears to an issue with lifetimes. A more full sample may be found here, but the relevant code is this:
struct Node<'a> {
data: i32,
children: RwLock<HashMap<String, Node<'a>>>,
parent: Option<&'a Node<'a>> //necessary, as I need to be able to recurse back up the tree
}
impl<'a> Node<'a> {
fn add_sequence(&'a self, key_list: Vec<String>, data: i32) {
let mut key_iter = key_list.iter();
let mut curr = self;
let last = loop {
let next = key_iter.next();
if let None = next {return;}
let key = next.unwrap();
if curr.children.read().unwrap().contains_key(key) {
curr = curr.children.read().as_ref().unwrap().get(key).unwrap();
} else {
break next.unwrap();
}
};
curr.add_child(last.to_string(), data);
}
}
This gives me the following error:
--> src/main.rs:22:24
|
11 | impl<'a> Node<'a> {
| -- lifetime `'a` defined here
...
22 | curr = curr.children.read().as_ref().unwrap().get(key).unwrap();
| ^^^^^^^^^^^^^^^^^^^^--------- - temporary value is freed at the end of this statement
| |
| creates a temporary which is freed while still in use
| argument requires that borrow lasts for `'a`
I have tried solutions such as the one described in this answer, but I haven't been able to get it to work, possibly due to the process being iterative rather than one-time. How can I fix this error?