簡體   English   中英

BigUint和“無法移出借用的內容”錯誤

[英]BigUint and “cannot move out of borrowed content” error

我嘗試使用BigUint遵循“ Rust by Example”的“迭代器”部分中描述的迭代器方法:

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結構一起使用?

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

也可以看看:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM