我有一个树结构,它在 RwLock 中使用 HashMap 来表示节点的子节点,但是我向下递归树以插入值的方法似乎存在生命周期问题。可以在此处找到更完整的示例,但相关代码如下:
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);
}
}
这给了我以下错误:
--> 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`
我已经尝试过诸如this answer中描述的解决方案,但我无法让它工作,可能是因为该过程是迭代的而不是一次性的。我该如何解决这个错误?