【发布时间】:2015-02-27 14:13:04
【问题描述】:
为了学习 Rust,我正在实现一个 AVL 树/字典。要插入一个新元素,我会下降到树中,直到找到可以插入它的节点。不幸的是,它抱怨了一些借用指针的问题,我在破译它们时遇到了麻烦。
我已经强调了发生的位置和错误。
enum AVLTree<T, U> {
Tree(T, U, Box<AVLTree<T, U>>, Box<AVLTree<T, U>>),
Empty,
}
impl<T, U> AVLTree<T, U>
where T: PartialOrd + PartialEq + Copy,
U: Copy
{
fn insert_element(&mut self, key: T, val: U) {
let new_node = AVLTree::Tree(key, val, Box::new(AVLTree::Empty), Box::new(AVLTree::Empty));
if let AVLTree::Empty = *self {
*self = new_node;
return;
}
let mut at = self;
loop {
match at {
&mut AVLTree::Tree(key2, _, ref mut left, ref mut right) => {
// ^~~~~~~~~~~~
// error: cannot borrow `at.2` as mutable more than once at a time
// ^~~~~~~~~~~~~
// error: cannot borrow `at.3` as mutable more than once at a time
if key < key2 {
if let AVLTree::Empty = **left {
*left = Box::new(new_node);
break;
}
at = &mut **left;
// error: cannot assign to `at` because it is borrowed
} else {
if let AVLTree::Empty = **right {
*right = Box::new(new_node);
break;
}
at = &mut **right;
// error: cannot assign to `at` because it is borrowed
}
}
&mut AVLTree::Empty => unreachable!(),
}
}
// Do something
}
}
解构at为什么要借用呢?为什么编译器会抱怨多个可变借用,而这种情况永远不会发生?如何编写此代码以避免此类错误?
【问题讨论】:
-
提问时请考虑创建MCVE。这有助于您了解问题的具体部分,也有助于回答者更快地理解问题。这是example for this case。
-
感谢您的提示,我以后会记住的。 (我不经常问问题,所以我有点尴尬)
-
别担心!我们都必须从某个地方开始。 ^_^
标签: rust