抱歉,如果这是一个愚蠢的问题,我对 Rust 还比较陌生,但我无法解决这个双重可变借用错误。 我正在尝试创建一个 AVL 树方法,找到适当的位置来插入新节点。 我不明白我需要做什么才能使第一个 borrow 放弃。
我正在尝试在没有 RC、RefCell 或 Unsafe 的情况下完成此操作,尽管我越来越不清楚我的方法是否可行。
pub fn find_pos(&mut self, key: &K) -> &mut Link<K, V>{
let mut current = &mut self.root;
while let Some(node) = current.as_mut() { // <- first mutable borrow
match node.key.cmp(&key) {
Ordering::Equal => break,
Ordering::Greater => {
current = &mut node.right;
},
Ordering::Less => {
current = &mut node.left;
},
}
};
current // <- second mutable borrow
}
我也尝试了类似于这里描述的解决方案,但没有成功。
pub fn find_pos(&mut self, key: &K) -> &mut Link<K, V> {
let mut current = &mut self.root;
loop {
let tmp = current;
if let Some(ref mut node) = *tmp {
match node.key.cmp(&key) {
Ordering::Equal => {
current = tmp;
break
},
Ordering::Greater => {current = &mut node.right},
Ordering::Less => {current = &mut node.left},
}
} else {
current = tmp;
break
}
}
current
}