Rust 锈病-在一个线性内条件突变
程序员注意: 我们都知道,一行程序总是能产生更好的代码。因此,在我学习锈的力量的过程中,我尝试为表示二进制树的结构创建一个插入函数。对于一个额外的挑战,我想让它变异树,而不是得到一个新的 结构如下所示:Rust 锈病-在一个线性内条件突变,rust,borrow-checker,Rust,Borrow Checker,程序员注意: 我们都知道,一行程序总是能产生更好的代码。因此,在我学习锈的力量的过程中,我尝试为表示二进制树的结构创建一个插入函数。对于一个额外的挑战,我想让它变异树,而不是得到一个新的 结构如下所示: pub type Node = i32; type Branch = Option<Box<BinaryTree>>; #[derive(Debug)] pub struct BinaryTree { node: Node, left: Branch,
pub type Node = i32;
type Branch = Option<Box<BinaryTree>>;
#[derive(Debug)]
pub struct BinaryTree {
node: Node,
left: Branch,
right: Branch
}
pub类型节点=i32;
类型分支=选项;
#[导出(调试)]
发布结构二叉树{
节点:节点,
左:分支,
右:分行
}
而我对插入函数的实现应该是:
impl BinaryTree {
pub fn insert(&mut self, node: Node) {
(if node <= self.node { &mut self.left } else { &mut self.right }) // get the correct branch
.as_deref_mut()
.map(|t| {t.insert(node); t}) // if the branch (Option) is Some, call insert onto the branch and return it
.get_or_insert(&mut Box::new(BinaryTree { node, left: None, right: None })); // if the branch is some (meaning it got mapped) then just return (do nothing), else insert a new Tree into the branch
}
}
impl二进制树{
发布fn插入(&mut self,节点:node){
(如果node调用映射
返回一个新的选项
,那么调用get\u或_insert
,只会设置这个新创建的选项的值
引用引用(这也体现在传递引用时&mut Box::new(…)
——您实际上需要一个值)
也就是说,您实际上需要一个&mut选项
来调用get\u或\u insert