【发布时间】: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