我试图实现一个二叉树,但是我坚持执行插入操作:
use std::cmp::PartialOrd;
type Link<T> = Option<Box<Node<T>>>;
struct Node<T: PartialOrd> {
val: T,
left: Link<T>,
right: Link<T>,
}
struct Tree<T: PartialOrd> {
root: Link<T>,
}
impl<T: PartialOrd> Tree<T> {
fn new() -> Self {
Tree { root: None }
}
fn add(&mut self, val: T) {
let mut prev: Option<&mut Node<T>> = None;
let mut cur = self.root.as_mut();
while let Some(boxed_node_ref) = cur {
if val < boxed_node_ref.val {
cur = boxed_node_ref.left.as_mut();
} else {
cur = boxed_node_ref.right.as_mut();
}
prev = Some(boxed_node_ref);
}
}
}
fn main() {
println!("It's ok...");
}
错误是:
error[E0499]: cannot borrow `**boxed_node_ref` as mutable more than once at a time
--> src/main.rs:30:25
|
24 | while let Some(boxed_node_ref) = cur {
| - first borrow ends here
25 | if val < boxed_node_ref.val {
26 | cur = boxed_node_ref.left.as_mut();
| ------------------- first mutable borrow occurs here
...
30 | prev = Some(boxed_node_ref);
| ^^^^^^^^^^^^^^ second mutable borrow occurs here
我不明白为什么它告诉我第二次借钱boxed_node_ref
。我想我正在移动它。