Rust -在一行代码中进行条件突变



rust程序员注意:

我们都知道,一行程序总是能写出更好的代码。因此,在我学习rust的过程中,我尝试为一个表示BinaryTree的结构体创建一个插入函数。对于一个额外的挑战,我想让它改变树,而不是得到一个新的。

结构体如下:

pub type Node = i32;
type Branch = Option<Box<BinaryTree>>;
#[derive(Debug)]
pub struct BinaryTree {
node: Node,
left: Branch,
right: Branch
}

而我的插入函数的实现应该是:

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
}
}

…它会编译,但实际上不会改变树。所以,问题是我哪里出错了,因为我明确地将分支声明为可变的。

更好的单行版本显然也受到追捧!

你对map的调用返回一个新的Option<&mut Box<BinaryTree>>,所以调用get_or_insert只设置这个新创建的Option引用引用的值(这也体现在你传递引用&mut Box::new(...)-你实际上想要一个值在那里)。

。你实际上需要一个&mut Option<Box<BinaryTree>>来调用get_or_insert

最新更新