【问题标题】:BigUint and "cannot move out of borrowed content" errorBigUint 和“无法移出借用内容”错误
【发布时间】:2018-05-21 03:12:07
【问题描述】:

我尝试遵循Rust by Example's Iterator section 中描述的迭代器方法和BigUint

extern crate num_bigint;

use num_bigint::{BigUint, ToBigUint};

struct FibState {
    a: BigUint,
    b: BigUint,
}

impl Iterator for FibState {
    type Item = BigUint;
    fn next(&mut self) -> Option<BigUint> {
        let b_n = self.a + self.b;
        self.a = self.b;
        self.b = b_n;
        Some(self.a)
    }
}

fn fibs_0() -> FibState {
    FibState {
        a: 0.to_biguint().unwrap(),
        b: 1.to_biguint().unwrap(),
    }
}

fn fib2(n: usize) -> BigUint {
    if n < 2 {
        n.to_biguint().unwrap()
    } else {
        fibs_0().skip(n - 1).next().unwrap()
    }
}

fn main() {
    println!("Fib1(300) = {}", fib2(300));
}

以上代码无法编译:

error[E0507]: cannot move out of borrowed content
  --> src/main.rs:13:19
   |
13 |         let b_n = self.a + self.b;
   |                   ^^^^ cannot move out of borrowed content

error[E0507]: cannot move out of borrowed content
  --> src/main.rs:13:28
   |
13 |         let b_n = self.a + self.b;
   |                            ^^^^ cannot move out of borrowed content

error[E0507]: cannot move out of borrowed content
  --> src/main.rs:14:18
   |
14 |         self.a = self.b;
   |                  ^^^^ cannot move out of borrowed content

error[E0507]: cannot move out of borrowed content
  --> src/main.rs:16:14
   |
16 |         Some(self.a)
   |              ^^^^ cannot move out of borrowed content

我不确定这是否是因为 BigUint 类型不是原始类型,因此它没有 Copy 特征。如何修改迭代器以使其与 FibState 结构一起使用?

【问题讨论】:

    标签: rust


    【解决方案1】:
    fn next(&mut self) -> Option<BigUint> {
        let b_next = &self.a + &self.b; 
        let b_prev = std::mem::replace(&mut self.b, b_next);
        self.a = b_prev;
        Some(self.a.clone())
    }
    
    1. BigUint 没有实现Copy,但Add trait 接受两个参数的值。 BigUint 也为引用实现了 Add,因此您可以取而代之的是对值的引用。

    2. 我们想将b 的当前值替换为b 的下一个值,但我们需要保留旧值。我们可以使用mem::replace

    3. 将旧的 b 值分配给 a 很简单。

    4. 现在我们希望返回a中的值,所以我们需要clone整个值。

    BigUint 类型不是原始类型,因此它没有 Copy 特征

    原始的东西和实现Copy 特征的东西彼此无关。用户类型可以实现Copy,一些原语不实现Copy

    另见:

    【讨论】:

      猜你喜欢
      • 2017-10-15
      • 2018-04-04
      • 1970-01-01
      • 1970-01-01
      • 2015-03-18
      • 2015-03-25
      • 1970-01-01
      • 2015-04-20
      • 1970-01-01
      相关资源
      最近更新 更多