【问题标题】:How to solve [E0382]: use of moved value in a for loop?如何解决 [E0382]:在 for 循环中使用移动值?
【发布时间】:2021-02-13 03:48:27
【问题描述】:

请帮我解决以下错误:

error[E0382]: use of moved value: `nd3`
  --> src/main.rs:21:21
   |
19 |     Node::Y { nd: nd3, max: max } => {
   |                   --- move occurs because `nd3` has type `std::boxed::Box<Node>`, which does not implement the `Copy` trait
20 |       for m in 0..max - 1 {
21 |         match recur(nd3) {
   |                     ^^^ value moved here, in previous iteration of loop

代码如下。请不要介意代码看起来毫无意义,因为我对其进行了简化:

enum Node {
  X { x: usize },
  Y { nd: Box<Node>, max: usize },
  Z { Nd: Vec<Box<Node>> },
}

fn recur(nd: Box<Node>) -> Result<usize, ()> {
  match *nd {
    /// ...
    Node::Y { nd: nd3, max: max } => {
      for m in 0..max - 1 {
        match recur(nd3) {
          Ok(y) => return Ok(y),
          _ => {}
        }
      }
      return Ok(123);
    }
    _ => {}
  }
  return Ok(0);
}

【问题讨论】:

    标签: rust borrow-checker ownership


    【解决方案1】:

    如果您有一个自有值 (nd),并且您对其进行迭代,然后再次对其进行迭代,您将收到错误,因为它已被移至循环的上一次迭代中。

    一种解决方案是为Node 派生Clone 特征。 Clone 是显式复制对象的常见特征:

    #[derive(Clone)]
    enum Node {
      X { x: usize },
      Y { nd: Box<Node>, max: usize },
      Z { Nd: Vec<Box<Node>> },
    }
    

    现在您可以在再次递归调用函数时克隆nd3

    Node::Y { nd: nd3, max: max } => {
      for m in 0..max - 1 {
        match recur(nd3.clone()) {
          Ok(y) => return Ok(y),
          _ => {}
        }
      }
      return Ok(123);
    }
    

    现在,您不会将拥有的值传递给循环的下一次迭代。相反,您传递的是完全相同的副本。另一种解决方案是借用价值。但是,对于较小的对象,克隆更容易。

    【讨论】:

    • 给 Rust 初学者的建议:克隆,无耻地克隆。熟悉这种语言,然后深吸一口气,开始借钱。学习所有权/借款已经够难了,你不想同时遇到其他问题。
    猜你喜欢
    • 2022-11-27
    • 2015-11-17
    • 2021-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-24
    • 2021-03-10
    相关资源
    最近更新 更多