rust - 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
结构一起使用?
解决方案
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
。
也可以看看:
推荐阅读
- c# - 使用 X509 密钥的文件加密
- php - PHPUnit Mock 'method' 方法返回 NULL
- azure - Azure 上的 IceCast 挂载点返回 404
- r - R Shiny Treemap,计算每组的人数
- excel - 如何调用 Excel 中的两个变量来抄送 Outlook 电子邮件?
- typescript - 如何排除要编译的文件,但要在 Typescript 中进行测试?
- json - Pentaho 数据集成 - 雪花 - 将字段转换为数据类型 VARIANT
- python - ModuleNotFoundError:没有名为“paypal”的模块
- python - PyLint 与 f 字符串
- bash - 如何在 xargs 中将函数作为参数传递?