Rust 将消费树转换为非消费树

Rust 将消费树转换为非消费树,rust,Rust,我已经创建了下面的树,使用深度优先遍历 这会导致第二次调用函数时出错: <anon>:10:5: 10:9 error: use of moved value: `root` [E0382] <anon>:10 root.depth_first_pre(); ^~~~ <anon>:9:5: 9:9 note: `root` moved here because it has type `TreeNode`, which

我已经创建了下面的树,使用深度优先遍历

这会导致第二次调用函数时出错:

<anon>:10:5: 10:9 error: use of moved value: `root` [E0382]
<anon>:10     root.depth_first_pre();
              ^~~~
<anon>:9:5: 9:9 note: `root` moved here because it has type `TreeNode`, which is non-copyable
<anon>:9     root.depth_first_pre();
             ^~~~
error: aborting due to previous error
:10:5:10:9错误:使用移动值:`root`[E0382]
:10根。深度优先于前();
^~~~
:9:5:9:9注意:`root`移到这里是因为它的类型为`TreeNode`,这是不可复制的
:9根深度优先于前();
^~~~
错误:由于上一个错误而中止
我的理解是,它在第一次函数调用时被移出,一旦超出该函数的作用域,就被取消分配

我该怎么做

我尝试将函数更改为引用self(
&self
),并将
.unwrap()
更改为
as\u ref()
,但这并没有解决我的问题。

它与您建议的更改配合得很好
添加为\u ref
,而不是将
unwrap
替换为
as\u ref

fn depth_first_pre(&self) {
    print!("{}, ", self.value);

    if self.left.is_some() {
        self.left.as_ref().unwrap().depth_first_pre();
    }

    if self.right.is_some() {
        self.right.as_ref().unwrap().depth_first_pre();
    }
}
然而,如果让,那么使用
将更为惯用:

fn depth_first_pre(&self) {
    print!("{}, ", self.value);

    if let Some(ref left) = self.left {
       left.depth_first_pre();
    }

    if let Some(ref right) = self.right {
        right.depth_first_pre();
    }
}

您应该删除
build\u tree
方法以生成一个。Just
let root=TreeNode{value:0,left:None,right:None}就足够了,其余的都不重要了。他说“将
.unwrap()
更改为
作为
”,而不是在
unwrap()
之前“添加
作为
”;你做了后者P@FrancisGagn唉,我猜我的大脑只是把它解析为“我用
作为_ref
”。
fn depth_first_pre(&self) {
    print!("{}, ", self.value);

    if self.left.is_some() {
        self.left.as_ref().unwrap().depth_first_pre();
    }

    if self.right.is_some() {
        self.right.as_ref().unwrap().depth_first_pre();
    }
}
fn depth_first_pre(&self) {
    print!("{}, ", self.value);

    if let Some(ref left) = self.left {
       left.depth_first_pre();
    }

    if let Some(ref right) = self.right {
        right.depth_first_pre();
    }
}