我正在尝试实现二叉树,以帮助自己熟悉 Rust 处理指针和内存的方式。我似乎无法弄清楚如何编写
put()
方法。这棵树应该从头开始在树的底部递归地插入数字,其中小数字向左插入,大数字向右插入。
无论
Box<T>
类可用的借用符号或方法的组合是什么,我似乎无法弄清楚如何在不违反借用系统的情况下插入新节点。它总是看起来像头,或者其他东西已经拥有,我不能在任何地方做任何可变引用&mut
,因为其他东西已经拥有或正在借用它。
我得到的最大错误是
Cannot make a mutable reference from & borrowed value
。有人告诉我使用盒子在堆上分配树内存,但我也不确定这是否正确。
代码示例:
struct Node {
pub data : i32,
pub children : (Box<Option<Node>>, Box<Option<Node>>)
}
struct BinaryTree {
pub head : Box<Option<Node>>,
depth : u32
}
impl BinaryTree {
fn BinaryTree() -> BinaryTree {
BinaryTree { head: Box::new(None), depth: 0 }
}
fn push(&mut self, data : i32) {
// Return location to add to and insert
let to_insert_into = Self::push_recursive(&mut self.head, data);
*to_insert_into = Box::new(Some(Node {data : data, children : (Box::new(None), Box::new(None))}));
//println!(*to_insert_into.)
}
fn push_recursive(current : &mut Box<Option<Node>>, data : i32) -> &mut Box<Option<Node>> {
// base case: if current node is empty place into it
if current.is_none() {
return current;
}
else {
// recursive case: if larger place node right, else place node left
let current_data = current.as_ref().as_ref().unwrap().data;
let next_child : &mut Box<Option<Node>>;
if data > current_data {
next_child = &mut current.as_ref().as_ref().unwrap().children.1;
}
else {
next_child = &mut current.as_ref().as_ref().unwrap().children.0;
}
return Self::push_recursive(next_child, data);
}
}
}
作为一名C/C++程序员,Rust让我很头疼。我不明白为什么人们对此如此大肆宣传。
我尝试移动函数,使用 Box 函数以及 Rust 的内置解引用函数。什么都没用,我仍然无法强制树可变并在树的底部添加一个节点。