BigUint和“无法摆脱借来的内容”的错误

时间:2018-05-21 03:12:07

标签: rust

我尝试使用Scientific and Engineering C++: An Introduction with Advanced Techniques and Examples跟踪Rust by Example's Iterator section中描述的迭代器方法:

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结构一起使用?

1 个答案:

答案 0 :(得分: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特征按值获取两个参数。 BigUint也会为Add实现参考,因此您可以改为引用这些值。

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

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

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

  5.   

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

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

    另见: