首页 > 解决方案 > BigUint 和“无法移出借用内容”错误

问题描述

我尝试遵循Rust by Example 的 Iterator 部分中描述的迭代器方法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

解决方案


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整个值。

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

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

也可以看看:


推荐阅读