I tried to follow the iterator approach described in Rust by Example's Iterator section with 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));
}
The above code does not compile:
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
I am not sure if it is due to the BigUint
type is not primitive thus it does not have the Copy
trait. How can I modify the iterator to make it works with the FibState
struct?