rust - 有没有办法交换 Rust 二叉搜索树中的节点?
问题描述
我正在研究 Rust 中的二叉搜索树实现,我正在尝试实现一个交换子节点的函数。
#[derive(Default)]
pub struct Node {
data: i32,
left: Option<Box<Node>>,
right: Option<Box<Node>>
}
impl Node {
fn print_data(&self) -> i32 {
self.data
}
fn default() -> Node { //function to help when instantiate node with no children
Node {
data: 0,
left: None,
right: None
}
}
fn set_left(&mut self, new_left: Option<Box<Node>>) -> () {
// If self.left was already a pointer, now we're losing it
// (memory leak).
self.left = new_left
// Node {data: self.data, left: new_left, right: &self.right}
}
fn set_right(&mut self, new_right: Option<Box<Node>>) -> () {
self.right = new_right
}
fn swap_childs(&mut self) -> () {
let tmpr = Some(self.right.unwrap());
let tmpl = Some(self.left.unwrap());
let nilr = self.right.take();
let nill = self.left.take();
self.right = tmpl;
self.left = tmpr;
}
}
这是我得到的错误:
error[E0507]: cannot move out of `self.right` which is behind a mutable reference
--> src/main.rs:43:19
|
43 | let tmpr = Some(self.right.unwrap());
| ^^^^^^^^^^
| |
| move occurs because `self.right` has type `std::option::Option<std::boxed::Box<Node>>`, which does not implement the `Copy` trait
| help: consider borrowing the `Option`'s content: `self.right.as_ref()`
error[E0507]: cannot move out of `self.left` which is behind a mutable reference
--> src/main.rs:44:19
|
44 | let tmpl = Some(self.left.unwrap());
| ^^^^^^^^^
| |
| move occurs because `self.left` has type `std::option::Option<std::boxed::Box<Node>>`, which does not implement the `Copy` trait
| help: consider borrowing the `Option`'s content: `self.left.as_ref()`
通过大量的试验和错误,我知道我的结构无法实现Copy
特征,因为我使用的是Option
. 这就是为什么我认为进行这种更改的最佳方法是在结构内,因此是 impl 函数swap_childs
。有一个更好的方法吗?这个功能甚至可以使用Option
和Box
不使用其他类型Rc
吗?
解决方案
推荐阅读
- maven - maven-dependency-plugin 中非常奇怪的 NullPointerException
- python - 覆盖 Python 属性注释
- c++ - C++ Clang 模板“使用未声明的标识符”编译器标志
- javascript - for-of 循环和异步函数的问题
- python - 使用 Python 生成最多 3 个命令行程序实例 - 如何等到它们完成
- javascript - 设置 document.cookie 什么都不做
- jwt - Keycloak 客户端映射器将 relam 名称显示为 JWT 令牌中的个人属性
- python-3.x - 如果在 docker 上开发,flask app 邮件密码不安全
- php - php pdo 如何从数据库中下拉并设置默认值
- unit-testing - 使用 MDX 和 graphql 数据测试 Gatsby 组件