[英]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())
}
BigUint
沒有實現Copy
,但是Add
特質按值接受兩個參數。 BigUint
為引用實現Add
,因此您可以取值的引用。
我們想替換的當前值b
與下一個值b
,但我們需要保持舊值。 我們可以使用mem::replace
。
將舊的b
值分配給a
很簡單。
現在,我們希望在返回值a
,所以我們需要clone
整個價值。
BigUint
類型不是原始類型,因此沒有Copy
特征
某些東西是原始的,而某些東西則實現了Copy
特性,它們之間沒有任何關系。 用戶類型可以實現Copy
而某些原語不能實現Copy
。
也可以看看:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.